我有一个多维数组,从那个数组我想从第一个数组的同一个id1创建一个新数组,并希望将所有匹配的子数组值与其元素
一起放入其内部数组以下是我拥有的数组:
Array
(
[0] => Array
(
[id1] => 109891
[id2] => 67
)
[1] => Array
(
[id1] => 828393
[id2] => 67
)
[2] => Array
(
[id1] => 828393
[id2] => 68
)
[3] => Array
(
[id1] => 816714
[id2] => 70
)
[4] => Array
(
[id1] => 816714
[id2] => 67
)
[5] => Array
(
[id1] => 816714
[id2] => 68
)
)
我想以这种方式输出:
Array
(
[109891] => Array
(
[0] => Array
(
[id2] => 67
)
)
[828393] => Array
(
[0] => Array
(
[id2] => 67
)
[1] => Array
(
[id2] => 68
)
)
[816714] => Array
(
[0] => Array
(
[id2] => 70
)
[1] => Array
(
[id2] => 67
)
[2] => Array
(
[id2] => 68
)
)
)
任何帮助都会得到赞赏
答案 0 :(得分:2)
原点数组:
$array = array(
array('id1' => '109891', 'id2' => '67'),
array('id1' => '828393', 'id2' => '67'),
array('id1' => '828393', 'id2' => '68'),
array('id1' => '816714', 'id2' => '70'),
);
使用这个foreach:
$new = array();
foreach($array as $element) {
$new[$element['id1']][] = array('id2' => $element['id2']);
}
或函数中的这个:
function editMyArray($array) {
$newArray = array();
foreach($array as $element) {
$newArray[$element['id1']][] = array('id2' => $element['id2']);
}
return $newArray;
}
输出:
echo "<pre>";
print_r($new);
echo "</pre>";
Array
(
[109891] => Array
(
[0] => Array
(
[id2] => 67
)
)
[828393] => Array
(
[0] => Array
(
[id2] => 67
)
[1] => Array
(
[id2] => 68
)
)
[816714] => Array
(
[0] => Array
(
[id2] => 70
)
)
)
答案 1 :(得分:2)
这应该这样做:
$output = array();
foreach($input as $r) {
$id1 = $r['id1'];
if(!isset($output[$id1])) {
$output[$id1] = array();
}
$output[$id1][] = array('id2' => $r['id2']);
}
print_r($output);
答案 2 :(得分:0)
使用以下测试代码:
$i = 0;
$sepr = 0;
$arr = array();
foreach($your_array as $your_reslut_array) {
$k = $i; $k = ($k > 0 ? $k-1 : 0);
foreach($your_reslut_array as $key => $value) {
if($key != "ID" && $value != $your_reslut_array[$k][$key]) {
$sepr++;
}
}
$arr[$sepr][] = $car;
$i++;
}
print_r($arr);