tags:

views:

48

answers:

4

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?

A: 

Instead of

$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);

Try

$aMemberships[$aMemb['ID']] = $aMemb['Name'];
Tim
+3  A: 

You need to change your $aMemberships assignment

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

If you want an an array

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

if you want a map.

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

GWW
Every answer was the same. Had trouble picking one to vote for. +1 for explaining that he was appending an array to an array.
steven_desu
A: 

Your existing code uses incremental key and uses the array as corresponding value. To make make $aMemberships an associative array with key as $aMemb['ID'] and value being $aMemb['Name'] you need to change

    $aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);

in the foreach loop to:

    $aMemberships[$aMemb['ID']] = $aMemb['Name']);
codaddict
A: 

Hi,

it prints an array of arrays because you are doing so in this line

$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);

where you [] after a variable your are indicating to assign the value in a new row of the array and you are inserting an other array into that row

so you can use the the examples the others haver already gave or you can use this method:

int array_push ( array &$array , mixed $var [, mixed $... ] )

here is an example that you can find in the api

<?php
$stack = array(0=>"orange",1=>"banana");
array_push($stack, 2=>"apple",3=>"raspberry");
print_r($stack);
?>

//prints
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

http://php.net/manual/en/function.array-push.php

mklfarha