Saturday, August 18, 2018

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'

Thanks very much in advance.

Solved

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

looking to your data

You should use just $id and $nombre

    foreach ($respuestajson['options'] as $id => $nombre) {
         $proyectosZP[$id] =  $nombre;
    }

You are testing the keys but you can access them directly :

foreach ($respuestajson['options'] as $opt) {
    $proyectosZP[$opt['label']] = $opt['value'];
}

Or, from the current output :

$output = array_combine(array_column($input_array, 'label'),
                        array_column($input_array, 'value'));

No comments:

Post a Comment