如何在php中使用相同的id连接此数组?

时间:2014-01-27 15:51:38

标签: php mysql arrays

阵列(

 [0]=>array(
     [id]=>1
     [name]=>aaa
     [address]=>AAA 
 )
 [1]=>array(
     [id]=>1
     [name]=>bbb
     [address]=>BBB 
 )
 [2]=>array(
     [id]=>2
     [name]=>ccc
     [address]=>CCC 
 )
 [3]=>array(
     [id]=>2
     [name]=>ddd
     [address]=>DDD 
 )
 [4]=>array(
     [id]=>3
     [name]=>eee
     [address]=>EEE 
 )

这是从数据库中选择的普通数组。 我想要这样的输出:

阵列(

[0]=>array(
    [id]=>1
    [dataArray] => array(
        [0]=>array(
             [name]=>aaa
             [address]=>AAA
        )
        [1]=>array(
             [name]=>bbb
             [address]=>BBB
        ) 
    )
)
[1]=>array(
    [id]=>2
    [dataArray] => array(
        [0]=>array(
             [name]=>ccc
             [address]=>CCC
        )
        [1]=>array(
             [name]=>ddd
             [address]=>DDD
        ) 
    )
)
[2]=>array(
    [id]=>3
    [dataArray] => array(
        [0]=>array(
             [name]=>eee
             [address]=>EEE
        ) 
    )
)

我怎样才能在php中实现这一目标?请帮忙。我尝试了in_array和array_key_exists来检查现有的id,但我无法做到。

2 个答案:

答案 0 :(得分:1)

看看这是否适用于你。

$results = array();

//loop through your array
foreach($yourArray as $row => $field) {

  //check if "id" is already set and store the index value it exist within
  $existing_index = NULL;
  foreach($results as $result_row => $result_field) {
    if ($result_field['id'] == $field['id']) {
      $existing_index = $result_row;
      break;
    }
  }

  if (isset($existing_index)) {
    //the "id" already exist, so add to the existing id
    $dataArrayIndex = count($results[$existing_index]['dataArray']);
    $results[$existing_index]['dataArray'][$dataArrayIndex]['name'] = $field['name'];
    $results[$existing_index]['dataArray'][$dataArrayIndex]['address'] = $field['address'];
  }
  else {
    //the "id" does not exist, create it
    $results_index = count($results);
    $results[$results_index]['id'] = $field['id'];
    $results[$results_index]['dataArray'][0]['name'] = $field['name'];
    $results[$results_index]['dataArray'][0]['address'] = $field['address'];
  }
}

答案 1 :(得分:0)

迭代数组并将值分配给新变量:

$newArray = array();
foreach ( $yourArray as $v ) {
    if ( !isset($newArray[$v['id']]) ) {
        $newArray[$v['id']] = array('id' => $v['id'], 'dataArray' => array());
    }
    $newArray[$v['id']]['dataArray'][] = array('name' => $v['name'], 'address' => $v['address']);
}
print_r($newArray);

请参阅PHP手册@ http://us1.php.net/manual/en/control-structures.foreach.php