array_push somewhere in multidimensional array

时间:2016-10-20 13:04:16

标签: php arrays algorithm multidimensional-array

I have a table which could be multidimensional.

"aggs":
        {"by_psh_time":
            {"terms":
                {"field":"date_time"},
            "aggs":
                {"by_psh_comm":
                    {"terms":
                        {"field":"psh_comm"},
                    "aggs":
                        {"sum_pmem":
                            {"sum":
                                {"field":"psh_pmem"}
                            },
                        "sum_pcpu":
                            {"sum":
                                {"field":"psh_pcpu"}
                            }
                        }


                    }
                }
            }
        }

For example, I have here 3 "aggs" but in practice the amount of aggs is not fixed. To create this JSON, I want to use table and then JSON encode it.

Problem, I don't know how to push something in "by_psh_comm" for example (I nee to detect where is by_psh_comm in my array, arr[], arr[][] or arr[][][] ....).

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

function pushIf(&$array, $value) {
       if (isset($array["aggs"]) {
          pushIf($array["aggs"], $value); //Recurse
       }
       if (isset($array["by_psh_comm"])) {
          $array[] = $value; //This is pushed in the same array that contains "by_psh_comm"
       }
}

pushIf($array, $value);

答案 1 :(得分:0)

非常感谢apokryfos!

这不完全是我需要的,但你认真地推动了我! :D如果有人需要,这就是结果!

function addAggs($parent_aggs, $toPush, $tab) {
        if(array_key_exists($parent_aggs, $tab)){
            if(!isset($tab[$parent_aggs]["aggs"])){
                $tab[$parent_aggs]["aggs"] = array();
            }
            array_push($tab[$parent_aggs]["aggs"], $toPush);
            return $tab;
        } else {
            foreach($tab as &$subTab){
                if (is_array(addAggs($parent_aggs, $toPush, $subTab))){
                   $subTab = addAggs($parent_aggs, $toPush, $subTab);
                   return $tab;
                  exit();
                }
            }
            return false;
        }
    }