Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The goal

Replace this:

(
    [0] => 'Header'
    [1] => 'Body'
)

For this:

['Header'] => Array
    (
        [0] => Hello!
    )

['Body'] => Array
    (
        [0] => This is the body
    )

The problem

I'm missing the logic and I think this is happening because I doesn't know the syntax.

The scenario

Follow the original array (preview):

Array
(
    [Title] => 'Hello!'
    [Layout] => 'Shared/_Master'
    [Section] => Array
        (
            [0] => 'Header'
            [1] => 'Body'
        )    
)

Code:

<?php 

$array = [
    'Title' => 'Hello', 
    'Layout' => 'Shared/_Master',
    'Section' => ['Header', 'Body']
    ];

$mineredSection = ['Header' => ['Hello!'], 'Body' => ['This is the body.']];

What did I already tried

I already tried this:

foreach ($array['Section'] as $index => $section) {
    $t[$section] = [array_values(array_filter($mineredSection))[$index]];
}

$a = array_replace($array['Section'], $t);

print_r($a);

The result is:

Array
(
    [0] => 'Header'
    [1] => 'Body'
    ['Header'] => Array
        (
            [0] => Hello!
        )

    ['Body'] => Array
        (
            [0] => This is the body
        )

)

Can someone give me an idea?

share|improve this question
    
Maybe array_combine is what you want? –  Rocket Hazmat Dec 4 '13 at 16:18
    
Maybe. I just doesn't know how to (technically) apply it in my case. –  Guilherme Oderdenge Dec 4 '13 at 16:18
    
What is $this->contents? –  Rocket Hazmat Dec 4 '13 at 16:21
    
$this->contents is ['Hello', 'This is the body']. My bad. –  Guilherme Oderdenge Dec 4 '13 at 16:30
    
Then you can just do array_combine($array['Section'], $this->contents); :-) P.S. Isn't $mineredSection already the array you want? –  Rocket Hazmat Dec 4 '13 at 16:31

2 Answers 2

up vote 1 down vote accepted

You're looking for array_combine. You pass it two arrays, what you want as the keys and what you want as the values.

$array['Section'] = array_combine($array['Section'], $this->contents);
share|improve this answer

Either this, or I'm not understanding what you're asking

$origarr = array('header', 'body');

foreach($origarr as $value){
    if ($value == 'header'){
        $header['header'] = array('hello'); 
    }
    if ($value == 'body'){
        $body['body'] = array('This is the body'); 
    }   
}

var_dump($header);
var_dump($body);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.