在php数组中替换

时间:2017-03-08 09:42:53

标签: php arrays

我想替换

                    [children] => Array
                                            (
                                            )

来自我的php数组...我试过

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

但是数组中没有任何事情发生。我应该如何从php数组替换空子..

我的php输出

               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
                                            (
                                            )

                                    )

                            )

                    )

            )

完整的PHP代码

            <?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);
                    ?>

预期产出

               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 基于建议的更新代码 - http://pastebin.com/mAkZ4q12

更新了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);

              ?>

最终找到了解决方案

         <?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;
              ?>

1 个答案:

答案 0 :(得分:1)

感谢您修改问题。

最好的做法是避免在同一个数组上多个循环来添加/删除元素。干。 - 不要重复自己

如果您不希望阵列中包含某些元素,请不要将它们放入其中。 如果你想要一个特定的数组结构,那就适当地构建一次。

我还没有对此进行过测试,但它应该只使用一个循环就能为您提供所需的数组结构和值。如果没有,请编辑您的问题进行解释,发送评论,然后我会进一步提供帮助。

$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);