0

$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
)

1 Answer 1

1

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

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

It should instead be:

$newarray[$categorylevel][] = $value['CategoryID'];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.