0

Hey guys I'm confused about how to create an array using specific keys from my pre-existing array.

Laravel controller

public function index()
{
    $content = Page::find(1)->content->toArray();

    return View::make('frontend.services', compact('content'));
}

$content is an array that looks similar to

array ( 
    0 => array ( 
        'id' => '1', 
        'page_id' => '1', 
        'name' => 'banner_heading', 
        'content' => 'some content', ), 
    1 => array ( 
        'id' => '2', 
        'page_id' => '1', 
        'name' => 'banner_text', 
        'content' => 'some other content' )
)

And I want it recreate this array to look like this

array ( 
    0 => array ( 
        'banner_heading' => 'some content' 
    ), 
    1 => array (  
        'banner_text' => 'some other content' 
    )
)

How can I move the keys name and content to equal their values as a single row in the array?

I greatly appreciate any advice.

1
  • You could achieve this format directly from the query by using the lists() method instead of toArray(). Page::find(1)->content->lists('content', 'name'); Commented Jul 18, 2014 at 16:48

3 Answers 3

3

PHP >= 5.5.0:

$result = array_column($content, 'content', 'name');

PHP < 5.5.0:

foreach($content as $key => $array) {
    $result[$key] = array($array['name'] => $array['content']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer @AbraCadaver! Thanks for including a way to make it work with the different versions. I have just implemented the one for PHP >= 5.5.0 and it worked perfectly.
1

You mean

$newContent = array();
foreach ($content as $record) {
    $newContent[] = array($record['name'] => $record['content']);
} 

?

Comments

0

I don't know Laravel, but i believe that your solutions should be similar to this :

$newArray= array(); 
foreach($content as $key => $value)
{ 
   $newArray[] = $value["banner_heading"];
} 
return View::make('frontend.services', compact('newArray'));

Or at least it should be something similar with this.

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.