因为输入有一个像这样的关联数组:
$array[0]['id'] = 0;
$array[0]['name'] = 'first name';
$array[0]['phone'] = '+1 515 111 111';
$array[0]['for_id'] = 1;
$array[1]['id'] = 1;
$array[1]['name'] = 'first name1';
$array[1]['phone'] = '+1 515 222 222';
$array[1]['for_id'] = 1;
$array[2]['id'] = 0;
$array[2]['name'] = 'first name2';
$array[2]['phone'] = '+1 515 333 333';
$array[2]['for_id'] = 1;
$array[3]['id'] = 0;
$array[3]['name'] = 'first name3';
$array[3]['phone'] = '+1 515 444 444';
$array[3]['for_id'] = 2;
$array[4]['id'] = 0;
$array[4]['name'] = 'first name4';
$array[4]['phone'] = '+1 515 555 555';
$array[4]['for_id'] = 2;
$array[5]['id'] = 0;
$array[5]['name'] = 'first name5';
$array[5]['phone'] = '+1 515 666 666';
$array[5]['for_id'] = 2;
如何根据$array[]['for_id']
的相同值将其拆分为N个单独的数组?
与$array1
一样,$array
包含$array[]['for_id'] == 1;
和$array2
$array[]['for_id'] == 2;
的所有元素?
答案 0 :(得分:1)
只需遍历数组并在新数组中使用相同的for_id收集每个项目。
$t = array();
foreach ($array as $item) {
if (!isset($t[$item['for_id']]) {
$t[$item['for_id']] = array();
}
$t[$item['for_id']][] = $item;
}
答案 1 :(得分:1)
这里有一个类似菲利普斯的方式但是正是你想要的,即获取变量的名称以匹配for_id键值
$array[0]['id'] = 0;
$array[0]['name'] = 'first name';
$array[0]['phone'] = '+1 515 111 111';
$array[0]['for_id'] = 1;
$array[1]['id'] = 1;
$array[1]['name'] = 'first name1';
$array[1]['phone'] = '+1 515 222 222';
$array[1]['for_id'] = 1;
$array[2]['id'] = 0;
$array[2]['name'] = 'first name2';
$array[2]['phone'] = '+1 515 333 333';
$array[2]['for_id'] = 1;
$array[3]['id'] = 0;
$array[3]['name'] = 'first name3';
$array[3]['phone'] = '+1 515 444 444';
$array[3]['for_id'] = 2;
$array[4]['id'] = 0;
$array[4]['name'] = 'first name4';
$array[4]['phone'] = '+1 515 555 555';
$array[4]['for_id'] = 2;
$array[5]['id'] = 0;
$array[5]['name'] = 'first name5';
$array[5]['phone'] = '+1 515 666 666';
$array[5]['for_id'] = 2;
foreach($array as $arr){
$int = $arr['for_id'];
$arrName = 'array' . $int;
if(!isset($$arrName ))
{
$$arrName =array();
}
array_push($$arrName, $arr);
}
echo 'First array ' . json_encode($array1);
echo 'Second array ' . json_encode($array2);