0

I have gotten the tree-array like that:

enter image description here

Now I want to convert it to an array like this:

array(
      1 => array('id'=>'1','parentid'=>0),
      2 => array('id'=>'2','parentid'=>0),
      3 => array('id'=>'3','parentid'=>1),
      4 => array('id'=>'4','parentid'=>1),
      5 => array('id'=>'5','parentid'=>2),
      6 => array('id'=>'6','parentid'=>3),
      7 => array('id'=>'7','parentid'=>3)
      );

I had already coded something like this:

private function _getOrderData($datas)
{
    $_data = [];
    static $i = 0;
    foreach ($datas as $data) {
        $i++;
        $rows = ['id' => $data['id'], 'pid' => isset($data['children']) ? $data['id'] : 0, 'menu_order' => $i];
        if(isset($data['children'])) {
            $this->_getOrderData($data['children']);
        }
        $_data[] = $rows;
    }
    return $_data;
}

But it didn't work

Cry~~

How can I fix my code to get the array? Thanks~

BTW, my English is pool.

So much as I don't know you can read my description of the problem or not.

2
  • 1
    . post your sample array instead of image Commented Jul 10, 2017 at 9:19
  • We need your actual array and also explain which is children and parent from your actual array.. Commented Jul 10, 2017 at 9:22

1 Answer 1

1

I had already solved this problem, Thx~

private function _getOrderData($datas, $parentid = 0)
{
    $array = [];
    foreach ($datas as $val) {
        $indata = array("id" => $val["id"], "parentid" => $parentid);
        $array[] = $indata;
        if (isset($val["children"])) {
            $children = $this->_getOrderData($val["children"], $val["id"]);
            if ($children) {
                $array = array_merge($array, $children);
            }
        }
    }
    return $array;
}

The array look like: array

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.