简体   繁体   中英

Creating Array Based off Multidimensional Array Levels

$array looks like this.

Array
 (
     [CategoryID] => 4352
     [CategoryLevel] => 3
     [CategoryName] => Tags
 )

Array
 (
     [CategoryID] => 3243
     [CategoryLevel] => 2
     [CategoryName] => Actions
 )

Array
 (
     [CategoryID] => 2342
     [CategoryLevel] => 3
     [CategoryName] => Tags
 )

and so forth.

I've tried with a foreach loop

$newarray = array();
foreach ($array as $key => $value) {
    $categorylevel = $value['CategoryLevel'];
    $newarray[][$categorylevel] = $categorylevel;
}

But the output looks like such:

Array
(
    [0] => Array
        (
            [3] => 4352
        )

    [1] => Array
        (
            [2] => 3243
        )

    [2] => Array
        (
            [3] => 2342
        )
        . . . . . . . .

Instead of my desired output of

Array
(
    [2] => Array
        (
            [0] => 3243
        )

    [3] => Array
        (
            [0] => 4352
            [0] => 2342
        )
        . . . . . . . .

How can I modify my foreach code to produce my desired output?

Simply putting it in the $newarray key only brings back the last iterations of the Category Levels value

$newarray = array();
foreach ($array as $key => $value) {
    $categorylevel = $value['CategoryLevel'];
    $newarray[$categorylevel] = $categorylevel;
}

output:

. . . . . . . .
. . . . . . . .
[4] => 5967
[5] => 6756
[6] => 9933
)

You have a very simple mistake. This line is wrong.

$newarray[][$categorylevel] = $categorylevel;

It should instead be:

$newarray[$categorylevel][] = $value['CategoryID'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM