문제

Basically I want to add a dynamic array inside of another array, here's my array :

$myarray = array(
        'options' => array( ),
    );

And here's the dynamic array :

$page = array(
array('id' => '1' ,'title'=>'Page1' ),
array('id' => '2' ,'title'=>'Page2' )
);

I want to $myarray to be like this :

$myarray = array(
        'options' => 
            array('1' => 'Page1' ,'2'=>'Page2' ),
);

Here's what I tried :

 foreach ($page as $key => $value) {
   $myarray['options'][]=array(
   "".$value['id']."" =>"".$value['title'].""
   );
}

Any help with this? Thanks.
Here's a codepad demo

도움이 되었습니까?

해결책

$myarray = [];

foreach($page as $key => $value) {
    $myarray['options'][$value['id']] = $value['title'];
}

다른 팁

Just try with:

$myarray['options'] = array_reduce($page, function($options, $item){
    $options[$item['id']] = $item['title'];
    return $options;
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top