PHP wrap array elements in separate arrays

Issue

I have the following array:

$arr = [
    "elem-1" => [ "title" => "1", "desc" = > "" ],
    "elem-2" => [ "title" => "2", "desc" = > "" ],
    "elem-3" => [ "title" => "3", "desc" = > "" ],
    "elem-4" => [ "title" => "4", "desc" = > "" ],
]

First I need to change the value from [ "title" => "1", "desc" = > "" ] to 1 (title’s value).

I did this using array_walk:

array_walk($arr, function(&$value, $key) {
    $value = $value["title"];
});

This will replace my value correctly. Our current array now is:

$arr = [
    "elem-1" => "1",
    "elem-2" => "2",
    "elem-3" => "3",
    "elem-4" => "4",
]

Now, I need to transform each element of this array into its own subarray. I have no idea on how to do this without a for loop. This is the desired result:

$arr = [
    [ "elem-1" => "1" ],
    [ "elem-2" => "2" ],
    [ "elem-3" => "3" ],
    [ "elem-4" => "4" ],
]

Solution

You can change your array_walk callback to produce that array.

array_walk($arr, function(&$value, $key) {
    $value = [$key => $value["title"]];
});

Run the transformed array through array_values if you need to get rid of the string keys.

$arr = array_values($arr);

Answered By – Don't Panic

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published