Pergunta

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

Foi útil?

Solução

$myarray = [];

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

Outras dicas

Just try with:

$myarray['options'] = array_reduce($page, function($options, $item){
    $options[$item['id']] = $item['title'];
    return $options;
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top