D
D
Denis2013-02-21 13:17:00
PHP
Denis, 2013-02-21 13:17:00

"Infinitely" nested array

Good afternoon!

There is an array of strings.
You need to put them into each other.

$data = array('str1', 'str2', 'str3');

$array = array('str1', 'sub' => array('str2', 'sub' => 'str3'));

How can I do that?

Answer the question

In order to leave comments, you need to log in

6 answer(s)
W
WEBIVAN, 2013-02-21
@WEBIVAN

$data = array('str1', 'str2', 'str3', 'str4', 'str5');
$c=count($data)-1;
$a='';
if($c==0)
  $a=array($data[0]);
else
  for($i=$c;$i>=0;$i--)
  {
    if($i==$c)
      $a=$data[$i];
    else
      $a=array($data[$i],'sub'=>$a);
  }

N
Nikita Gusakov, 2013-02-21
@hell0w0rd

function str_tree($arr, $i = 0)
{
  $res = array();
  if( isset($arr[$i]) ){
    $res[] = $arr[$i++];
    $res['sub'] = str_tree($arr, $i);
  }
  return $res;
}

Here's a recursive version
of PS even the second one:
function str_tree($arr, $i = 0)
{
  return isset($arr[$i]) ? array($arr[$i++], 'sub' => str_tree($arr, $i)) : NULL;
}

W
WEBIVAN, 2013-02-21
@WEBIVAN

After additional examples, it turns out that your original example was incorrect, since the last element is now not a string, but an array.
For this case, the code is a bit simpler

$data = array('str1', 'str2', 'str3', 'str4', 'str5');
$c=count($data)-1;
$a='';
for($i=$c;$i>=0;$i--)
{
  if($i==$c)
    $a=array($data[$i]);
  else
    $a=array($data[$i],'sub'=>$a);
}
print_r($a);

M
MiXei4, 2013-02-21
@MiXei4

> There is an array of lines. You need to invest them in each other.
Who are they? Strings? An array of strings somewhere? Strings to an array? :) The problem is not clear.

A
Alexey Akulovich, 2013-02-21
@AterCattus

You can approach from the end:

$data = array('str1', 'str2', 'str3', 'str4');

$result = array(end($data));
while (false !== ($i = prev($data))) {
    $result = array($i, 'sub'=>$result);
}

A
akral, 2013-02-21
@akral

There is an array_reduce for something like this :

$my = array_reduce(array_reverse($data), function($result, $item) {
        return array($item, 'sub' => $result);
}, array());

It is not clear why the last array in the task does not have an empty subone, but if this is really necessary, then we select it specially:
$my = array_reduce(array_reverse(array_slice($data, 0, -1)), function($result, $item) {
        return array($item, 'sub' => $result);
}, array_slice($data, -1));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question