Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 371
tmartin314 Avatar asked Sep 06 '25 11:09

tmartin314


2 Answers

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.

like image 159
GWW Avatar answered Sep 10 '25 06:09

GWW


Associative array in foreach statement:

foreach($nodeids as $field => $value) {

  $field_data[$field]=$value;

}

Output:

Array(
$field => $value,
$field => $value
...
);

insertion in CodeIgniter:

$res=$this->db->insert($bundle_table,$field_data);
like image 45
ShivarajRH Avatar answered Sep 10 '25 08:09

ShivarajRH