0

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

1 Answer 1

0

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

4
  • I get 2 errors. Warning: array_keys() expects parameter 1 to be array, null given and Notice: Undefined offset: for each row Commented Nov 28, 2014 at 14:29
  • do you have the same number of arrays in $data data as you do in $choices ? Commented Nov 28, 2014 at 14:32
  • What I have is a variable that decides which choice is made. I get that array by key using the choice made and then with those array keys, i want to swap so 'apple become 'Red Apple' etc. I hope this makes sense Commented Nov 28, 2014 at 14:58
  • Really close....except my $choices array has got the values updated instead of the keys Commented Nov 28, 2014 at 15:08

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.