programmer
programmer

Reputation: 47

Replacement in the php array

i want to replace

                    [children] => Array
                                            (
                                            )

from my php array...i tried with

              $array=str_replace('[children] => Array
                                            (
                                            )',' ',$nestedArray);
                print_r($array);

but nothing happened in the array..how should i replace the empty children from php array..

my php output

               Array
            (
                [0] => Array
                    (
                        [id] => 44
                        [name] => அகடம்
                        [parent] => 
                        [color] => red
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 45
                                        [name] => மோசடி
                                        [parent] => 44
                                        [color] => red
                                        [children] => Array
                                            (
                                            )

                                    )

                                [1] => Array
                                    (
                                        [id] => 46
                                        [name] => சூழ்ச்சி
                                        [parent] => 44
                                        [color] => red
                                        [children] => Array
                                            (
                                            )

                                    )

                                [2] => Array
                                    (
                                        [id] => 47
                                        [name] => அநீதி
                                        [parent] => 44
                                        [color] => red
                                        [children] => Array
                                            (
                                            )

                                    )

                                [3] => Array
                                    (
                                        [id] => 48
                                        [name] => பொல்லாங்கு
                                        [parent] => 44
                                        [color] => red
                                        [children] => Array
                                            (
                                            )

                                    )

                            )

                    )

            )

complete php code

            <?php

            $con=mysqli_connect("localhost","root","pass","data");       

            if (mysqli_connect_errno())                
              {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
              }
               $name=$_GET['editor'];
             $sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
            $r = mysqli_query($con,$sql);
                    $data = array();

                    while($row = mysqli_fetch_assoc($r)) {
                      $data[] = $row;
                    }

                     function buildtree($src_arr, $parent_id = 0, $tree = array())
            {
                foreach($src_arr as $idx => $row)
                {
                    if($row['parent'] == $parent_id)
                    {
                        foreach($row as $k => $v)
                            $tree[$row['id']][$k] = $v;
                        unset($src_arr[$idx]);
                        $tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
                    }
                }
                ksort($tree);
                return $tree;
            }

            function insertIntoNestedArray(&$array, $searchItem){

                if($searchItem['parent'] == 0){
                    array_push($array, $searchItem);
                    return;
                }
                if(empty($array)){ return; }
             array_walk($array, function(&$item, $key, $searchItem){
                if($item['id'] == $searchItem['parent']){
                        array_push($item['children'], $searchItem);
                        return;
                    }
                    insertIntoNestedArray($item['children'], $searchItem);
            }, $searchItem);
            }
            $nestedArray = array();
            foreach($data as $itemData){
             //$nestedArrayItem['value'] = $itemData['value'];
              $nestedArrayItem['id'] = $itemData['id'];
                $nestedArrayItem['name'] = $itemData['name'];
                $nestedArrayItem['parent'] = $itemData['parent'];
              $nestedArrayItem['tooltip'] = $itemData['tooltip'];
                 $nestedArrayItem['color'] = $itemData['color'];
                 $nestedArrayItem['level'] = $itemData['level'];

                $nestedArrayItem['children'] = array();
            //$data[]=$dat;
                insertIntoNestedArray($nestedArray, $nestedArrayItem);
            }
            header('Content-Type: application/json');

                            print_r( $nestedArray);
                    ?>

expected output

               Array
            (
                [0] => Array
                    (
                        [id] => 44
                        [name] => அகடம்
                        [parent] => 
                        [color] => red
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 45
                                        [name] => மோசடி
                                        [parent] => 44
                                        [color] => red


                                    )

                                [1] => Array
                                    (
                                        [id] => 46
                                        [name] => சூழ்ச்சி
                                        [parent] => 44
                                        [color] => red


                                    )

                                [2] => Array
                                    (
                                        [id] => 47
                                        [name] => அநீதி
                                        [parent] => 44
                                        [color] => red


                                    )

                                [3] => Array
                                    (
                                        [id] => 48
                                        [name] => பொல்லாங்கு
                                        [parent] => 44
                                        [color] => red

                                    )

                            )

                    )

            )

PASTBIN FOR DETAILS - http://pastebin.com/mqyfbdsq UPDATED CODE BASED ON SUGGESTION - http://pastebin.com/mAkZ4q12

updated php

                <?php
           $con=mysqli_connect("localhost","root","admin321","data");       

            if (mysqli_connect_errno())                
              {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
              }
               $name=$_GET['editor'];
             $sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
             $i=-1;
            $r = mysqli_query($con,$sql);
                    $data = array();

            while($row = mysqli_fetch_assoc($r)) {
                         if($row['parent']==""){
                        ++$i;
                       }
          foreach($row as $k=>$v){
      if($row['parent']==""){
            $tree[$i][$k]=$v;
        }else{
            $tree[$i]['children'][$k]=$v;
        }
                      $data[] = $row;
                    }
            }
        function buildtree($src_arr, $parent_id = 0, $tree = array())
            {
                foreach($src_arr as $idx => $row)
                {
                    if($row['parent'] == $parent_id)
                    {
                        foreach($row as $k => $v)
                            $tree[$row['id']][$k] = $v;
                        unset($src_arr[$idx]);
            $tree[$row['id']]['children'] = 
              buildtree($src_arr, $row['id']);
                    }
                }
                ksort($tree);
                return $tree;
            }

            function insertIntoNestedArray(&$array, $searchItem){

                if($searchItem['parent'] == 0){
                    array_push($array, $searchItem);
                    return;
                }
                if(empty($array)){ return; }
             array_walk($array, function(&$item, $key, $searchItem){
                if($item['id'] == $searchItem['parent']){
                        array_push($item['children'], $searchItem);
                        return;
                    }
                    insertIntoNestedArray($item['children'], $searchItem);
            }, $searchItem);
            }
            $nestedArray = array();
            foreach($data as $itemData){
             //$nestedArrayItem['value'] = $itemData['value'];
              $nestedArrayItem['id'] = $itemData['id'];
                $nestedArrayItem['name'] = $itemData['name'];
                $nestedArrayItem['parent'] = $itemData['parent'];
              $nestedArrayItem['tooltip'] = $itemData['tooltip'];
                 $nestedArrayItem['color'] = $itemData['color'];
                 $nestedArrayItem['level'] = $itemData['level'];

                $nestedArrayItem['children'] = array();
            //$data[]=$dat;
                insertIntoNestedArray($nestedArray, $nestedArrayItem);
            }
            header('Content-Type: application/json');

            $json= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
            echo $json = substr($json, 1, -1);

              ?>

FINALLY FOUND THE SOLUTION

         <?php


            $con=mysqli_connect("localhost","root","pass","data");       

            if (mysqli_connect_errno())                
              {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
              }
               $name=$_GET['input'];
             $sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
            $r = mysqli_query($con,$sql);
                    $data = array();
                    while($row = mysqli_fetch_assoc($r)) {
                     $data[] = $row;
                     }  
         function buildtree($src_arr, $parent_id = 0, $tree = array())
            {
                foreach($src_arr as $idx => $row)
                {
                    if($row['parent'] == $parent_id)
                    {
                        foreach($row as $k => $v)
                            $tree[$row['id']][$k] = $v;
                        unset($src_arr[$idx]);
        $tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
                    }
                }
                ksort($tree);
                return $tree;
            }

            function insertIntoNestedArray(&$array, $searchItem){

                if($searchItem['parent'] == 0){
                    array_push($array, $searchItem);
                    return;
                }
                if(empty($array)){ return; }
             array_walk($array, function(&$item, $key, $searchItem){
                if($item['id'] == $searchItem['parent']){
                        array_push($item['children'], $searchItem);
                        return;
                    }
                    insertIntoNestedArray($item['children'], $searchItem);
            }, $searchItem);
            }
            $nestedArray = array();
            function array_remove_empty($haystack)
            {
                foreach ($haystack as $key => $value) {
                    if (is_array($value)) {
                $haystack[$key] =    array_remove_empty($haystack[$key]);
                    }

                    if (empty($haystack[$key])) {
                        unset($haystack[$key]);
                    }
                }

                return $haystack;
            }
            foreach($data as $itemData){

              $nestedArrayItem['id'] = $itemData['id'];
                $nestedArrayItem['name'] = $itemData['name'];
                $nestedArrayItem['parent'] = $itemData['parent'];
              $nestedArrayItem['tooltip'] = $itemData['tooltip'];
                 $nestedArrayItem['color'] = $itemData['color'];
                  $nestedArrayItem['level'] = $itemData['level'];

                $nestedArrayItem['children'] = array();
                insertIntoNestedArray($nestedArray, $nestedArrayItem);
            }
            header('Content-Type: application/json');
            $jj=(array_remove_empty($nestedArray));
            $json=json_encode($jj,JSON_UNESCAPED_UNICODE);
            echo $json;
              ?>

Upvotes: 0

Views: 118

Answers (1)

mickmackusa
mickmackusa

Reputation: 47854

Thank you for editing your question.

The best course of action is to avoid multiple loops over the same array just to add/remove elements. D.R.Y. - Don't Repeat Yourself

If you don't want to have certain elements in your array, don't ever put them in. If you want a specific array structure, build it appropriately, one time.

I haven't tested this, but it should provide you with the desired array structure and values while using just one loop. If not, please edit your question to explain, send me a comment, and I'll assist further.

$name=$_GET['editor'];
// $_GET must be validated/santized before used in query...
$sql="SELECT * FROM phptab where value LIKE '%".$name."%' ORDER BY `parent`,`id`";
$r=mysqli_query($con,$sql);
$i=-1;
$j=-1;
while($row=mysqli_fetch_assoc($r)){
    if($row['parent']=="0"){
        ++$i;  // if a parent row, increment its numeric key
    }else{
        ++$j;  // if a child row, increment its numeric key
    }
    foreach($row as $k=>$v){
        if($row['parent']=="0"){
            // parent row data goes in outer array
            $tree[$i][$k]=$v;
        }else{
            // child row parent's children (inner) array with its numeric key 
            $tree[$i]['children'][$j][$k]=$v;
        }
    }
}
header('Content-Type: application/json');
$json=json_encode($tree,JSON_UNESCAPED_UNICODE);
echo $json=substr($json,1,-1);

Upvotes: 1

Related Questions