1

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.

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'
            )
        )
    )
)

2 Answers 2

1

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

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

1 Comment

@user2856332, why don't recursion?
1

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)));

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.