0

I have an array like so:

$input = array("visit", "outdoor", "parks-trailer");
$input_content = "A Value for last array element for input array."

$another_input = array("visit", "outdoor");
$another_input_content = "A Value for last array element for $input_content array."

And I have some text to assign to the last element of the array, once built.

Basically, what I need is the returned array to be like this:

$output = array(
    "visit" => array(
        "outdoor" => array(
            "A Value for last array element for $input_content array."
            "parks-trailer" => "A Value for last array element for input array."
        )
    )
);

How can I do this from values of an $input array that will always be 1 dimensional.

$content = 'My Value';
$output = array();
$flipped = array_flip($input);
$count = count($input) - 1;

foreach($flipped as $key => $flip)
{
    if ($count >= $key)
        $output[$key] = $content;
    else
        $output[$key] = array();
}

The problem here is that array_flip does work, but it doesn't do multidimensional here? And so array_flip transforms to array('visit' => 0, 'outdoor' => 1, 'parks-trailer' => 2), but I'm at a loss on how to get it to do multidimensional array, not singular.

I need to loop through multiples of these and somehow merge them into a global array, the answer given in here is not the same.

So, I need to merge each 1 of these into another array, keeping the values, if they exist. array_merge does not keep the values, array_merge_recursive does not keep the same key structure. How to do this?

Solomon Closson
  • 6,111
  • 14
  • 73
  • 115

1 Answers1

1

I'm not sure sure why you would want such thing, but this is an option:

$ar = ['a', 'b', 'c'];

function arrayMagicFunction($ar, $last_string = 'STRING') {
    $ret = $last_string;
    $ar = array_reverse($ar);
    foreach ($ar as $v) {
        $ret = [$v => $ret];
    }
    return $ret;
}
var_dump(arrayMagicFunction($ar, 'A Value here'));

Output:

array(1) {
  'a' =>
  array(1) {
    'b' =>
    array(1) {
      'c' =>
      string(12) "A Value here"
    }
  }
}
Dekel
  • 60,707
  • 10
  • 101
  • 129