我有一个数组:
$ar = array(
0 => array('id' => '1', 'pname' => 'text'),
1 => array('id' => '2', 'pname' => 'text2'),
2 => array('id' => '2', 'pname' => 'text3'),
3 => array('id' => '3', 'pname' => 'text4'),
4 => array('id' => '4', 'pname' => 'text5'),
5 => array('id' => '4', 'pname' => 'text6'),
6 => array('id' => '4', 'pname' => 'text7'),
);
我想得到这样的数组:
$result = array(
0 => array('id' => '1', 'pname' => 'text'),
1 => array('id' => '2', 'pname' => array('text2', 'text3')),
3 => array('id' => '3', 'pname' => 'text4'),
4 => array('id' => '4', 'pname' => array('text5', 'text6', 'text7'))
);
需要帮助!如何迭代第一个数组以获得像第二个数组的结果?
答案 0 :(得分:4)
简单的foreach循环应该可以解决问题,例如:
$array_1 = array(
array('id' => '1', 'pname' => 'text'),
array('id' => '2', 'pname' => 'text2'),
array('id' => '2', 'pname' => 'text3'),
array('id' => '3', 'pname' => 'text4'),
array('id' => '4', 'pname' => 'text5'),
array('id' => '4', 'pname' => 'text6'),
array('id' => '4', 'pname' => 'text7'),
);
$iterated_array = array();
foreach ($array_1 as $value) {
$iterated_array[$value['id']]['pname'][] = $value['pname'];
}
print_r($iterated_array);