Search code examples
phpforeachkeyvaluepair

How to create Array with Key Value Pairs in PHP


Anybody could help me with this issue in PHP?

My code:

for ($i=0; $i < count($respuestajson['options']); $i++) {
    foreach ($respuestajson['options'][$i] as $id => $nombre) {
        if($id == "label" || $id == "value"){
            $proyectosZP[$i][$id] = $nombre;
        }
    }
}

My current output is:

array (size=2)
  0 => 
    array (size=2)
      'label' => 'CEV'
      'value' => '10100'
  1 => 
    array (size=2)
      'label' => 'CEX'
      'value' => '10004'

I need this output:

array (size=2)
  'CEV' => '10100'
  'CEX' => '10004'

Solution

  • Simply traverse your array in foreach and combine them

    $input_array = array(
        array("label"=>"CEV",'value' => '10100'),array("label"=>"CEX",'value' => '10004')
        );
    
    $new_array = array();
    foreach($input_array as $elements)
    {
        $new_array[$elements['label']]=$elements['value'];
    }
    print_r($new_array);
    

    Or from your code:

    for ($i=0; $i < count($respuestajson['options']); $i++) {   
                $proyectosZP[$respuestajson['options'][$i]['label']] = $respuestajson['options'][$i]['value'];
    }