0

There is an array, how to make so that the array key is the same as the id?

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Phones
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 2
            [title] => Apple
            [parent] => 1
        )

    [2] => Array
        (
            [id] => 5
            [title] => Samsung
            [parent] => 1
        )
)

I tried to do so, but it turns out the other way around, id becomes the same as the array key. It should be the other way around.

foreach ($statement as $key => $value) {
    $statement[$key]['id'] = $key;
}

2 Answers2

0
foreach($array as $key => $val){
 $new_array[$val['id']] = $val;
}

$array = $new_array;
sathia
  • 2,192
  • 2
  • 24
  • 42
  • beware that if you don't have unique ids you'll find only the last value on the new array. also, accept answer :) – sathia Aug 17 '16 at 17:52
0

The part where you were mistaken is the usage of $key. Please see that $key refers to the keys of the main array i.e 0, 1, 2.

Since we need the value corresponding to key id, $value['id'] becomes the key of our result array $newArray. Just use a new variable and store it in that.

Code:

$newArray = array();
foreach ($statement as $value) {
    $newArray[$value['id']] = $value;
}

Output:

 Array
(
   [1] => Array
    (
        [id] => 1
        [title] => Phones
        [parent] => 0
    )
   [2] => Array
    (
        [id] => 2
        [title] => Apple
        [parent] => 1
    )

    [5] => Array
     (
        [id] => 5
        [title] => Samsung
        [parent] => 1
      )
)
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32