phparraysmultidimensional-arrayassociative-array

Generate an associative 2d array with incremented column values using a flat array as first level keys


Is it possible to pad an array with incrementing numbers? For example

$myArr = ["red", "green", "blue"];
$type = "colour";

I want to somehow merge these and add a sort order so I end up with the following

Array
(
    [red] => Array
        (
            [type] => "colour"
            [sort] => 1
        )
    [green] => Array
        (
            [type] => "colour"
            [sort] => 2
        )
    [blue] => Array
        (
            [type] => "colour"
            [sort] => 3
        )
)

So far I have only managed:

$additional_data = array_pad([], count($myArr), ['type_id' => $type_id]);
$data = array_combine($myArr, $additional_data);

which is yielding:

Array
(
    [red] => Array
        (
            [type] => "colour"
        )
    [green] => Array
        (
            [type] => "colour"
        )
    [blue] => Array
        (
            [type] => "colour"
        )
)
    

I know I can do it by iterating through colours, but wondered if it could be done without a loop.


Solution

  • The version which you posted to solve this problem always has 1 as the sort_order.

    $myArr = ["red", "green", "blue"];
    $type_id = "colour";
    $sort = 0;
    
    $additional_data = array_pad([], count($myArr), ['type_id' => $type_id, 'sort_order' => ++$sort]);
    $data = array_combine($myArr, $additional_data);
    print_r($data);
    

    outputs...

    Array
    (
        [red] => Array
            (
                [type_id] => colour
                [sort_order] => 1
            )
    
        [green] => Array
            (
                [type_id] => colour
                [sort_order] => 1
            )
    
        [blue] => Array
            (
                [type_id] => colour
                [sort_order] => 1
            )
    
    )
    

    You could then process the result with array_walk to correct the values...

    $myArr = ["red", "green", "blue"];
    $type_id = "colour";
    $sort = 0;
    
    $additional_data = array_pad([], count($myArr), ['type_id' => $type_id, 'sort_order' => ++$sort]);
    $data = array_combine($myArr, $additional_data);
    $sort = 1;
    array_walk($data, function (&$item, $key) use(&$sort) {
        $item['sort_order'] = $sort++;
    });
    
    print_r($data);
    

    Which corrects it to.

    Array
    (
        [red] => Array
            (
                [type_id] => colour
                [sort_order] => 1
            )
    
        [green] => Array
            (
                [type_id] => colour
                [sort_order] => 2
            )
    
        [blue] => Array
            (
                [type_id] => colour
                [sort_order] => 3
            )
    
    )