phparraysmultidimensional-arrayfilteringflatten

Create a flat associative array from two columns of a 2d array and filter out blacklisted values


I am using the following foreach loop to populate a new array with filtered data.

foreach ($aMbs as $aMemb) {
    $ignoreArray = array(1, 3);
    if (!in_array($aMemb['ID'], $ignoreArray)) { 
        $aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
    }
}

The problem is that it is producing a 2-dimensional array, but I want to have a flat, associative array.

If $aMbs had the following data:

[
    ['ID' => 1, 'Name' => 'Standard'],
    ['ID' => 2, 'Name' => 'Silver'],
    ['ID' => 3, 'Name' => 'Gold'],
    ['ID' => 4, 'Name' => 'Platinum'],
    ['ID' => 5, 'Name' => 'Unobtainium'],
]

The desired output would be:

[
    2 => 'Silver',
    4 => 'Platinum',
    5 => 'Unobtainium',
]

How can I achieve this?


Solution

  • You need to change your $aMemberships assignment

    $aMemberships[] = $aMemb['Name']; 
    

    If you want an array

    $aMemberships[$aMemb['ID']] = $aMemb['Name'];
    

    if you want a map.

    What you are doing is appending an array to an array.