-4

I have
$x = array('a', 'b', 'c');

I need to convert this to:

array (size=1)
  'a' => 
    array (size=1)
      'b' => 
        array (size=1)
          'c' => boolean true

I need to create multidimensional array with single child\parent, first one will be the main\root key of array (it's 'a') the last one's value should be 'bool true', that's all i need

Pleas help, thank u

5
  • 1
    It is impossible to answer to this, since the conversion rules are completely vague. Commented Jun 22, 2016 at 13:04
  • 1
    c is not boolean it is a string your example. You could do $x = array('a', 'b', 'c' => true);. Your question is unclear though. Commented Jun 22, 2016 at 13:08
  • Okay sorry for low amount of info, i need to create multidimensional array with single child\parent, first one will be the main parent (it's 'a') the last one's value should be 'bool true', that's all i need Commented Jun 22, 2016 at 13:10
  • Possible duplicate of PHP convert one dimensional array into multidimensional Commented Jun 22, 2016 at 13:11
  • This is a typical X => Y Problem. meta.stackexchange.com/questions/66377/what-is-the-xy-problem Commented Jun 22, 2016 at 13:21

2 Answers 2

2

I don't know why do you need to do that but this should help:

function transform($array)
{
 if (empty($array)) {
  return true;
 }

 return [array_shift($array) => transform($array)];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Upvoted this; whilst it's a vague question this is a nice approach.
Thank u very much!
1

Try:

$tmpArr = array('a', 'b', 'c');
$arr = array();
$ref = &$arr;
foreach ($tmpArr as $key) {
    $ref[$key] = array();
    $ref = &$ref[$key];
}
$ref = true;
$tmpArr = $arr;
print '<pre>';print_r($tmpArr);
print '<pre>';var_dump($tmpArr);
exit;

Output:

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => 1
                )

        )

)

var_dump result:

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      &bool(true)
    }
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.