0

I'm trying to pass some of the values from theOptions array and drop them into a new array called $theDefaults.

$theOptions = array(

    'item1' => array('title'=>'Title 1','attribute'=>'Attribute 1','thing'=>'Thing 1'),
    'item2' => array('title'=>'Title 2','attribute'=>'Attribute 2','thing'=>'Thing 2'),
    'item3' => array('title'=>'Title 3','attribute'=>'Attribute 3','thing'=>'Thing 3')

);

So, $theDefaults array should look like this:

$theDefaults = array(

    'Title 1' => 'Attribute 1',
    'Title 2' => 'Attribute 2',
    'Title 3' => 'Attribute 3'

);

However, I cannot figure out how to do this. Have tried this but it is clearly not quite working.

$theDefaults = array();

foreach($theOptions as $k=>$v) {
    array_push($theDefaults, $v['title'], $v['attribute']); 
}

but when I run this...

foreach($theDefaults as $k=>$v) {
    echo $k .' :'.$v;
}

It returns this. 0 :Title 11 :Attribute 12 :Title 23 :Attribute 24 :Title 35 :Attribute 3

Looks to be soooo close, but why are the numbers in the array?

1 Answer 1

6

It's even simpler than that:

$theDefaults = array();
foreach($theOptions as $v) {
    $theDefaults[$v['title']] = $v['attribute']; 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Noting that the issue is that array_push pushes all arguments after the first to the end of the array.
Oooops, beat me to it by few seconds. :)
wow. that was fast. Thanks! it worked. apparently i can declare your answer correct in 8 minutes.

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.