php - array_push 多维数组中的某处

标签 php arrays algorithm multidimensional-array

我有一个可以是多维的表。

"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"}
                            }
                        }


                    }
                }
            }
        }

例如,我这里有 3 个“aggs”,但实际上 aggs 的数量并不固定。要创建此 JSON,我想使用表,然后对其进行 JSON 编码。

问题,例如,我不知道如何在“by_psh_comm”中推送某些内容(我需要检测 by_psh_comm 在我的数组 arr[]、arr[][] 或 arr[][][] 中的位置。 ...)。

最佳答案

尝试以下操作:

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

关于php - array_push 多维数组中的某处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40155284/

相关文章:

php获取接口(interface)方法

时间戳为零的 PHP 日期返回 1 小时

代码在 C 中未按预期工作

algorithm - 是否有将图像直方图转换为原始图像的算法?

algorithm - 是否存在可以生成所有可能排列的交换序列?

ruby - 如何降低这个函数的复杂度?

php - PDOException'无效参数号: parameter was not defined

php 函数在每个空行处分割数组?

c++ - 将 token 存储到数组中

python - 使用邻域和对 3D 数组进行子采样