简体   繁体   中英

PHP build multidimensional array from

I have a small array that I was hoping to divide into a multidimensional array. I have goofed around with some foreach loops, counted loops, and recursion with no luck. I clearly need to learn more.

Can I take an array like this:

array(
(int) 0 => 'red',
(int) 1 => 'white'
(int) 2 => 'blue'
)

And make it multidimensional like this:

array(
'AND' => array(
    'LIKE ' => 'red',
    'AND' => array(
        'LIKE ' => 'white',
        'AND' => array(
            'LIKE ' => 'blue'
        )
    )
)
)

Any help is appreciated.

You can do it with recursion:

function multify($arr)
{
    if(count($arr)<=1)
    {
        return array('LIKE'=>array_pop($arr));
    }
    return array('LIKE'=>array_pop($arr), 'AND'=>multify($arr));
}

$arr = array('red', 'white', 'blue');
print_r(array('AND'=>multify($arr)));

Some magic up here with references without recursion.

$array = array('red', 'white', 'blue');

$new_array = array();
$temp_array = &$new_array;
foreach ($array as $item)
    {
    $temp_array = &$temp_array['and'];
    // $temp_array value now equals to null, 
    // and it's refers to parent array item with key 'and'
    $temp_array['like'] = $item;
    }
unset($temp_array);
print_r($new_array);

Demo

您可以使用

<pre><?php print_r($array); ?></pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM