如何转置数组元素? [英] How to transpose array elements?
本文介绍了如何转置数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在php中有一个数组$categories
,如下所示.
I have an array $categories
in php as follows.
Array
(
[item_name] => Array
(
[0] => I-Phone
[1] => samsung
[2] => nokia
[3] => htc
)
[item_price] => Array
(
[0] => 30.00
[1] => 20
[2] => 10
[3] => 15
)
)
我想将其元素转置为
Array
(
[0] => Array
(
[item_name] => I-Phone
[item_price] => 30.00
)
[1] => Array
(
[item_name] => samsung
[item_price] => 20
)
[2] => Array
(
[item_name] => nokia
[item_price] => 10
)
[2] => Array
(
[item_name] => htc
[item_price] => 15
)
)
我尝试使用foreach循环,但无法正常工作.
I've tried using foreach loop but not working.
$count=0;
foreach ($categories as $key=> $category)
{
$categories[$count] = $category[$key];
$categories[$count] = $category[$key];
$count++;
}
推荐答案
这里是一种方法:
$categories = array(
'item_name' => array('I-Phone', 'samsung', 'nokia','htc'),
'item_price' => array('30.00', '20', '10', '15')
);
$out = array();
foreach($categories as $key => $a){
foreach($a as $k => $v){
$out[$k][$key] = $v;
}
}
echo '<pre>';
print_r($out);
echo '</pre>';
这篇关于如何转置数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文