0

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

2 Answers 2

4
$myarray = [];

foreach($page as $key => $value) {
    $myarray['options'][$value['id']] = $value['title'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

you are welcome. ;) Please accept it so anyone who wants to learn can see my answer accepted.
1

Just try with:

$myarray['options'] = array_reduce($page, function($options, $item){
    $options[$item['id']] = $item['title'];
    return $options;
});

Comments

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.