Create associative array from Foreach Loop PHP

Viewed 102500

I have this foreach loop:

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

This prints out the right fields but they are arrays inside arrays. I need the foreach loop to output a simple array like this one:

$aMemberships = array('1' => 'Standard', '2' => 'Silver');

What am I doing wrong?

6 Answers

You get key and value of an associative array in foreach loop and create an associative with key and value pairs.

$aMemberships=array();//define array
foreach($aMbs as $key=>$value){
    $ignoreArray = array(1,3);
    if (!in_array($key,$ignoreArray)){ 
        $aMemberships[$key] = $value;
    }
}

It will give you an expected output:

array('1' => 'Standard', '2' => 'Silver');
Related