PHP change array keys with key values from another array

1.1k views Asked by At

I have 2 arrays. What I am trying to do is replace the $choices array keys with respective $data keys

This is what I expect to see. I hope this makes sense

$choices = array(
    'fruits' => array(
        'Red Apple' => '',
        'Yellow Banana' => '',
        'Orange Orange' => '',
    ),
    ...
    ...
);

and this is my code

$data = array(
    'fruits' => array(
        'apple' => 'Red Apple',
        'banana' => 'Yellow Banana',
        'orange' => 'Orange Orange',
    ),
    'vegetables' => array(
        'potato' => 'Brown Potato',
        'carrot' => 'Orange Carrot',
        'cabbage' => 'Green Cabbeage',
    ),
    'vehicles' => array(
        'car' => 'Small Car',
        'plane' => 'Large Plane',
        'train' => 'Medium Train',
    )
);

$choices = array(
    'fruits' => array(
        'apple' => 'gjhgfj',
        'banana' => 'gjfgjfg',
        'orange' => 'gfjfgjfg'
    ),
    'vegetables' => array( 
        'potato' => 'gjfgj',
        'carrot' => 'gjfgj',
        'cabbage' => 'gjfgj'
    ),
    'vehicles' => array(
        'car' => 'gjfgj',
        'plane' => 'gfjgfjfgj',
        'train' => 'gjfgjghj'
    )
);

$choice = 'fruits';

if(array_key_exists($choice, $choices)) {
    $array = $choices[$choice];

    //this is where i want to swap array keys
}

UPDATE

Based on @andrew's answer, this is what I have now

if(array_key_exists($choice, $choices)) {
    $array = $choices[$choice];

    //this is where i want to swap array keys
    for ($i = 0; $i < count($choices); $i++) {
       $array[$i] = array_combine(array_keys($data[$i]), $array[$i]);
    }
}
1

There are 1 answers

4
andrew On BEST ANSWER

Probably something like this:

foreach ($data as $key => $val){
   $choices[$key] = $val;
   array_flip($choices[$key]);
}

with array_combine and array_flip will work

Edited, not 100% sure what you're trying to achieve but this may help