28

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?

1
  • Please explain why '1' => 'Standard' would exist in the output if only elements with non-blacklisted keys are pushed into the output array. Commented May 31, 2024 at 5:34

6 Answers 6

50

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Every answer was the same. Had trouble picking one to vote for. +1 for explaining that he was appending an array to an array.
what if query return id and name how to loop throug so the id and name can settle in one <td value = "id">name</td>
23

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);

2 Comments

Why are we talking about CodeIgniter? Where did you dream up these variables and array structure? Why not skip the loop entirely and just declare: $field_data = $nodeids;??? $field => $value, $field => $value is a very misleading presentation of the output.
My tip for Codeigniter insertion at the time of posting on Jan 21, 2013. Please ignore that statement now.
10

Instead of

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

Try

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

Comments

4

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']);

1 Comment

what if query return id and name how to loop through so the id and name can settle in one <td value = "id">name</td>
0

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');

1 Comment

Please explain why '1' => 'Standard' would exist in the output if only elements with non-blacklisted keys are pushed into the output array.
0

Instead of performing a filtering process on each iteration of your loop, you can create a new associative array with array_column(), then filter out the blacklisted keys with array_diff_key() after flipping the blacklist. The advantage in doing so is that the process will always only take 3 function calls instead of 1 + n function calls.

Code: (Demo)

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

$ignoreArray = [1, 3];

var_export(
    array_diff_key(
        array_column($aMbs, 'Name', 'ID'),
        array_flip($ignoreArray)
    )
);

Output:

array (
  2 => 'Silver',
  4 => 'Platinum',
  5 => 'Unobtainium',
)

If you'd rather keep the foreach() loop, then the earlier answers are perfectly fine. Here's a foreach() style using array destructuring. The advantage of this syntax (if you have additional irrelevant columns), is that you don't need to access all data in each row and you set up convenient temporary variables. Demo

$ignoreArray = [1, 3];
$aMemberships = [];
foreach ($aMbs as ['ID' => $id, 'Name' => $name]) {
    if (!in_array($id, $ignoreArray)) {
        $aMemberships[$id] = $name;
    }
}
var_export($aMemberships);
// same output as the previous snippet

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.