Mitch
Mitch

Reputation: 1394

Laravel/PHP create an array from array

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.

Upvotes: 0

Views: 4093

Answers (3)

Ovidiu B
Ovidiu B

Reputation: 106

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.

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

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']);
}

Upvotes: 3

cornelb
cornelb

Reputation: 6066

You mean

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

?

Upvotes: 1

Related Questions