phparrays

Get column of values from a 2d array


How can I reduce this multidimensional array by isolating the branch_id column values?

My array data:

[
    'list_data' => [
        ['branch_id' => '3'],
        ['branch_id' => '4'],
    ]
]

Desired result:

['list_data' => ['3', '4']]

Solution

  • This is a case for array_map:

    $array = [
        'list_data' => [
            [ 'branch_id' => 3],
            [ 'branch_id' => 4],
        ]
    ];
    
    $array['list_data'] = array_map(function($item) {
        return $item['branch_id'];
    },$array['list_data']);
    var_dump($array);
    

    Or array_column

    $array['list_data'] = array_column($array['list_data'], 'branch_id');
    var_dump($array);