2

The goal

Make this:

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

The problem

I'm missing the logic.

The scenario

My arrays are:

$keys = ['Title', 'Layout', 'Section', 'Section'];
$values = ['Hello!', 'Shared/_Master', 'Header', 'Body'];

Thanks in advance.

1
  • what have u tried!!!except missing the logic Commented Dec 4, 2013 at 14:19

1 Answer 1

1

This is taken from the comments in the manual page of array_combine and appears to do the job you need (although the function name choice is a bit odd in my opinion!):

<?php

$keys = array('Title', 'Layout', 'Section', 'Section');
$values = array('Hello!', 'Shared/_Master', 'Header', 'Body');

function array_combine_($keys, $values)
{
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
    return    $result;
}

echo '<pre>';
print_r(array_combine_($keys, $values));
echo '</pre>';
?>

Produces

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

)
Sign up to request clarification or add additional context in comments.

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.