将值存储在唯一键的多维数组中



如何使用下面所示的数组显示以下内容?

牧师

key=>0, member_id, member_name

执事

key=>1, member_id, member_name
Key =>2, member_id, member_name

这是数组

array (size=3)
  0 => 
    array (size=4)
      'category_name' => string 'Pastors' (length=7)
      'member_id' => string '3' (length=1)
      'member_name' => string 'Tiny Marshall' (length=13)
      'member_email' => string 'jconley@nowhere.com' (length=19)
  1 => 
    array (size=4)
      'category_name' => string 'Deacons' (length=7)
      'member_id' => string '1' (length=1)
      'member_name' => string 'Jeremiah Conley' (length=15)
      'member_email' => string 'jconley@nowhere.com' (length=19)
  2 => 
    array (size=4)
      'category_name' => string 'Deacons' (length=7)
      'member_id' => string '2' (length=1)
      'member_name' => string 'Marcy Conley' (length=12)
      'member_email' => string 'jconley@nowhere.com' (length=19)
下面是我用来构建数组的代码:
while( $row = mysql_fetch_assoc( $result ) )
{
    $staff[$i] = array
    (
        'category_name' => $row['category_name'],
        'member_id' => $row['member_id'],
        'member_name' => $row['member_name'],
        'member_email' => $row['member_email'],
    );
    $i++;
}

这是最终的解决方案:

$category_name = array();       
    foreach ($staff as $member) {
        if (!in_array( $member['category_name'], $category_name )) 
        {
            echo '<h1>' . $member['category_name'] . '</h1>';
            $category_name[] = $member['category_name'];
        } 
        echo $member['member_id'] . ', ' . $member['member_name'] . '<br />';
    }

使用foreach来遍历$staff数组

$pastors = array();
$deacons = array();
foreach ($staff as $member) {
  if ($member['category_name'] == 'Pastors') {
    $pastors[] = $member['member_id'] . ', ' . $member['member_name'];
  } else if ($member['category_name'] == 'Deacons') {
    $deacons[] = $member['member_id'] . ', ' . $member['member_name'];
  }
}
文档

相关内容

  • 没有找到相关文章

最新更新