我有一个我从MySQL查询创建的php关联数组。它看起来像这样;
array(
(int) 0 => array(
'items' => array(
'index_no' => '1'
),
(int) 0 => array(
'NumItems' => '2'
)
),
(int) 1 => array(
'items' => array(
'index_no' => '2'
),
(int) 0 => array(
'NumItems' => '3'
)
)
看起来不必要的复杂。我想简化它看起来像这样;
array(
(int) 0 => array(
'index_no' => '1',
'NumItems' => '2'
)
),
(int) 1 => array(
'index_no' => '2',
'NumItems' => '3'
)
)
如何在php中完成?我一直坚持这个问题。如果我有,我会发布我的答案。如果有人能给我一些起点,我将不胜感激。非常感谢你。
答案 0 :(得分:3)
你可以尝试一下:
$tempArray = array(
(int) 0 => array(
'items' => array(
'index_no' => '1'
),
(int) 0 => array(
'NumItems' => '2'
)
),
(int) 1 => array(
'items' => array(
'index_no' => '2'
),
(int) 0 => array(
'NumItems' => '3'
)
));
$newArray = array();
$i=0;
foreach($tempArray as $temp) {
$newArray[$i]['index_no'] = $temp['items']['index_no'];
$newArray[$i]['NumItems'] = $temp[0]['NumItems'];
$i++;
}
print "<pre>";
print_r($newArray);
答案 1 :(得分:2)
试试这个
<?php $res=array(array('item'=>1,'number'=>5),array('item'=>2,'number'=>56));
$final_array =array();
$i=0;
foreach ($res as $val)
{
foreach($val as $key=>$val2)
{
$final_array[$i][$key] = $val2;
}$i++;
}
print_r($final_array);
?>
答案 2 :(得分:2)
这是你的解决方案。
$diffArray = array(
(int) 0 => array(
'items' => array(
'index_no' => '1'
),
(int) 0 => array(
'NumItems' => '2'
)
),
(int) 1 => array(
'items' => array(
'index_no' => '2'
),
(int) 0 => array(
'NumItems' => '3'
)
));
print_r($diffArray);
$getArray = array();
foreach ($diffArray as $simArray) {
$getArray['index_no'][] = $simArray['items']['index_no'];
$getArray['NumItems'][]= $simArray[0]['NumItems'];
}
print_r($getArray);
答案 3 :(得分:1)
$newArray = array();
foreach ($array as $items) {
$temp = array('index_no' => $items['index_no']);
$temp = array_merge($temp, $items[0]);
$newArray[] = $temp;
}
它会将所有键添加到index - 0