-7

I have a comma separated string like

$str = "word1,word2,word3";

And i want to make a parent child relationship array from it. Here is an example:

enter image description here

3
  • Can you at least draw the Array you want to achieve? Commented Sep 2, 2015 at 10:16
  • sports[0]=> cricket[0]=> hockey[0]=> football[0]=> tennis Commented Sep 2, 2015 at 10:21
  • Check stackoverflow.com/questions/31357558/… Commented Sep 2, 2015 at 10:22

4 Answers 4

2

Try this simply making own function as

$str = "word1,word2,word3";
$res = [];

function makeNested($arr) {
    if(count($arr)<2)
        return $arr;
    $key = array_shift($arr);
    return array($key => makeNested($arr));
}

print_r(makeNested(explode(',', $str)));

Demo

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

Comments

0
function tooLazyToCode($string)
{
    $structure = null;
    foreach (array_reverse(explode(',', $string)) as $part) {
        $structure = ($structure == null) ? $part : array($part => $structure);
    }

    return $structure;
}

Comments

0

Please check below code it will take half of the time of the above answers:

<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
    if($prev != $i){
        $result = array($arr[$i] => $result);
    } else {
        $result = array ($arr[$i]);
    }
    $prev = $i;
}
echo '<pre>',print_r($result),'</pre>';

Comments

0

Here is another code for you, it will give you result as you have asked :

<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
    if($prev != $i){
        if($i == 0){
            $result = array($arr[$i] => $result);
        }else{
            $result = array(array($arr[$i] => $result));
        }

    } else {
        $result = array ($arr[$i]);
    }
    $prev = $i;
}
echo '<pre>',print_r($result),'</pre>';

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.