PHP How can I pass values from one array to another?

喜你入骨 提交于 2019-12-12 05:26:36

问题


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:


It's even simpler than that:

$theDefaults = array();
foreach($theOptions as $v) {
    $theDefaults[$v['title']] = $v['attribute']; 
}


来源:https://stackoverflow.com/questions/15697292/php-how-can-i-pass-values-from-one-array-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!