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

时间:2014-06-14 21:43:28

标签: php arrays multidimensional-array

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

牧师

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 />';
    }

1 个答案:

答案 0 :(得分:0)

使用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'];
  }
}

documentation