1

i am stuck,....

i have an array like this:

$myArray['red'][0] = "valueRed0";
$myArray['red'][1] = "valueRed1";
$myArray['blue'][0] = "valueBlue0";
$myArray['blue'][1] = "valueBlue1";
$myArray['green'][0] = "valueGreen0";
$myArray['green'][1] = "valueGreen1";
$myArray['green'][top][0] = "valueGreenTop0";
$myArray['green'][top][1] = "valueGreenTop1";
$myArray['green'][bottom][0] = "valueGreenBottom0";
$myArray['green'][bottom][1] = "valueGreenBottom1";

As output i need:

array(
'red/valueRed0',
'red/valueRed1',
'blue/valueBlue0',
'blue/valueBlue1',
'green/valueGreen0',
'green/valueGreen1',
'green/top/valueGreenTop0',
'green/top/valueGreenTop1',
'green/bottom/valueGreenBottom0',
'green/bottom/valueGreenButtom1'
)

so this means: if the key is a string, it has to be the folder. If the key is a integer the value has to be ne new value.

It's important that it is recursive to interprate different sized arrays.

Anybody can help me with this, i can't solve this recursive thing.... ?

0

1 Answer 1

2

Here is an example of how it could be done

<?php
$myArray['red'][0] = "valueRed0";
$myArray['red'][1] = "valueRed1";
$myArray['blue'][0] = "valueBlue0";
$myArray['blue'][1] = "valueBlue1";
$myArray['green'][0] = "valueGreen0";
$myArray['green'][1] = "valueGreen1";
$myArray['green']['top'][0] = "valueGreenTop0";
$myArray['green']['top'][1] = "valueGreenTop1";
$myArray['green']['bottom'][0] = "valueGreenBottom0";
$myArray['green']['bottom'][1] = "valueGreenBottom1";

print_r(flatten($myArray));

function flatten($data,$keys=array()){
        $out=array();
        foreach($data as $key=>$val){
                if(!is_array($val)){
                        $out[] = implode("/",$keys)."/".$val;
                }else{
                        $out = array_merge($out,flatten($val,array_merge($keys,array($key))));
                }
        }
        return $out;
}

Output:

Array
(
    [0] => red/valueRed0
    [1] => red/valueRed1
    [2] => blue/valueBlue0
    [3] => blue/valueBlue1
    [4] => green/valueGreen0
    [5] => green/valueGreen1
    [6] => green/top/valueGreenTop0
    [7] => green/top/valueGreenTop1
    [8] => green/bottom/valueGreenBottom0
    [9] => green/bottom/valueGreenBottom1
)
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.