0

我有数组 1,它应该是 2

有没有人有想法/解决方案?

我需要 foreach 还是 for 循环?

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'];
    }

感谢所有的帮助!

4

3 回答 3

2
$output=array();
foreach($array as $k=>$v)
{
  $output[$v['category_id']]=$v['category'];
}

echo "<pre />";
print_r($output);

演示1

演示 2

对于多维结果:

$output=array();
foreach($array as $k=>$v)
{
  $output[][$v['category_id']]=$v['category'];
}

echo "<pre />";
print_r($output);
于 2013-05-14T06:45:23.803 回答
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
        )

)
于 2013-05-14T06:45:57.000 回答
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" } 
于 2013-05-14T06:47:39.253 回答