如何将关联数组转换为其他数组?
这是我的数组
$array=Array (
services => Array ( [0] => 6, [1] => 1, [2] => 3 ),
subservices => Array ( [0] => 'No data',[1] => 2 ,[2] => 'No data' ),
price=> Array ( [0] => 124, [1] => 789, [2] => 895 ),
);
我想转换为
Array (
[0] => Array ( [services] => 6, [subservices] => 'No data', [price] => 124 )
[1] => Array ( [services] => 1, [subservices] => 2, [price] => 789 )
[2] => Array ( [services] => 3, [subservices] => 'No data', [price] => 895 )
)
怎么办?
答案 0 :(得分:1)
$outArray=array();
for($i=0;$i<count($sourceArray['services']);$i++)
{
$outArray[]=array('services'=>$sourceArray['services'][$i],'subservices'=>$sourceArray['subservices'][$i],'price'=>$sourceArray['price'][$i]);
}
答案 1 :(得分:0)
这是一种动态方法。这还将允许您的子数组中包含其他值。
希望有帮助:
$array = array (
'services' => Array ( '0' => 6, '1' => 1, '2' => 3),
'subservices' => Array ( '0' => 'No data', '1' => 2, '2' => 'No data'),
'price' => Array ( '0' => 124, '1' => 789, '2' => 895)
);
//Get array keys.
$keys = array_keys($array);
//Iterate through the array.
for($i = 0; $i < count($array); $i++){
//Iterate through each subarray.
for($j = 0; $j < count($array[$keys[$i]]); $j++){
//Here we are checking to see if you have more data per element than your initial key count.
if($keys[$j]){
$index = $keys[$j];
} else {
$index = $j;
}
//Append results to the output array.
$results[$i][$index] = $array[$keys[$i]][$j];
}
}
echo '<pre>';
print_r($results);
echo '</pre>';
这将输出:
Array
(
[0] => Array
(
[services] => 6
[subservices] => 1
[price] => 3
)
[1] => Array
(
[services] => No data
[subservices] => 2
[price] => No data
)
[2] => Array
(
[services] => 124
[subservices] => 789
[price] => 895
)
)