Create associative array from Foreach Loop PHP

前端 未结 6 1558
盖世英雄少女心
盖世英雄少女心 2020-12-23 17:43

I have this foreach loop:

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


        
相关标签:
6条回答
  • 2020-12-23 18:07

    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

    0 讨论(0)
  • 2020-12-23 18:14

    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.

    0 讨论(0)
  • 2020-12-23 18:15

    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);
    
    0 讨论(0)
  • 2020-12-23 18:21

    Instead of

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

    Try

    $aMemberships[$aMemb['ID']] = $aMemb['Name'];
    
    0 讨论(0)
  • 2020-12-23 18:21

    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']);
    
    0 讨论(0)
  • 2020-12-23 18:21

    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');
    
    0 讨论(0)
提交回复
热议问题