我有数组1,它应该是2
有没有人有想法/解决方案?
我需要foreach还是for loop?
1
Array
(
[0] => Array
(
[category_id] => 5
[category] => Pages
)
)
必须:
Array
(
[0] => Array
(
[5] => Pages
)
)
我有这个,但这个工作......
for($x = 0; $x <= $counter; $x++){
foreach ($Categories[$x] as $key => $value){
echo $key.' '. $value.'<br>';
}
$test[$x]['category_id'] .= $Categories[$x]['category'];
}
感谢您的帮助!
答案 0 :(得分:2)
$output=array();
foreach($array as $k=>$v)
{
$output[$v['category_id']]=$v['category'];
}
echo "<pre />";
print_r($output);
用于多维结果:
$output=array();
foreach($array as $k=>$v)
{
$output[][$v['category_id']]=$v['category'];
}
echo "<pre />";
print_r($output);
答案 1 :(得分:2)
代码:
<?php
$arr = array(
array(
'category_id' => 5 ,
'category' => 'Pages',
),
);
$new = array();
foreach ($arr as $item) {
$new[] = array(
$item['category_id'] => $item['category']
);
}
print_r($new);
结果:
Array
(
[0] => Array
(
[5] => Pages
)
)
答案 2 :(得分:1)
正如你所说,你需要一个foreach循环来操纵你的数组。
实施例
$array = array
(
'0' => array
(
'category_id' => '5',
'category' => 'Pages'
)
);
$new_array = array();
foreach($array as $val)
{
$new_array[$val['category_id']] = $val['category'];
}
var_dump($new_array);
这将输出
array(1) { [5]=> string(5) "Pages" }