Reputation: 913
$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
)
Upvotes: 0
Views: 22
Reputation: 17378
You have a very simple mistake. This line is wrong.
$newarray[][$categorylevel] = $categorylevel;
It should instead be:
$newarray[$categorylevel][] = $value['CategoryID'];
Upvotes: 1