Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Array multidimensional if array_combine has duplicated key

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.

Upvotes: 2

Views: 614

Answers (1)

Clart Tent
Clart Tent

Reputation: 1309

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
        )

)

Upvotes: 1

Related Questions