重写多维数组以匹配另一个多维数组的格式

时间:2014-07-30 07:06:23

标签: php arrays multidimensional-array

让我们说我有一个看起来像这样的多维数组:

{
    "hello" : "world",
    "foo" : {
        "foo": {
            "foo": "bar"
        }
    },
    "some" : "value",
    "other" : {
        "other" : "value"
    }
}

我想通过这个数组并更改它的结构/值/格式以匹配基于此骨架数组的格式:

{
    "hello" : "",
    "foo" : "",
    "some" : {
        "some" : ""
    }
}

这样最终输出就像这样:

{
    "hello" : "world",
    "foo" : "bar",
    "some" : {
        "some" : "value"
    }
}

我已经使用array_intersect_key()来删除骨架数组中不存在的额外字段,然后使用array_replace_recursive()添加初始数据集中缺少但存在于骨架中的字段阵列。

但我不知道如何确保初始数据和骨架数组中存在的条目与骨架的结构相匹配。

这样的事情可以在(可能是一个递归的)循环中完成,它可以遍历初始数据并弄清楚它自己如何重写它所看到的任何键/值, 没有 硬编码,如:

if($key1 == "some") {
    $final["some"]["some"] = $initial["some"];
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为这是可能的,但前提是我们假设您从阵列中找到第一个键。否则,如果价值很多,可能很难找到价值。

例如,此代码:

<?php

$in
    = [
    "hello" => "world",
    "foo"   => [
        "foo" => [
            "foo" => "bar"
        ]
    ],
    "some"  => "value",
    "other" => [
        "other" => "value"
    ]
];

$out
    = [
    "hello" => "",
    "foo"   => "",
    "some"  => [
        "some" => ""
    ]
];


var_dump(fill($in, $out));


function fill($in, $out)
{
    foreach ($out as $k => $v) {
        if (!is_array($v)) {
            $out[$k] = find($in, $k);
        } else {
            $out[$k] = fill($in, $v);
        }
    }
    return $out;
}

function find($array, $needle)
{
    foreach ($array as $k => $v) {
        if (!is_array($v)) {
            if ($k == $needle) {
                return $v;
            }
        } else {

            $result = find($v, $needle);
            if ($result !== false) {
                return $result;
            }
        }
    }
    return false;
}

你会得到:

  

array(3){[&#34; hello&#34;] =&gt; string(5)&#34; world&#34; [&#34;富&#34;] =&GT; string(3)&#34; bar&#34;   [&#34;一些&#34;] =&GT; array(1){[&#34; some&#34;] =&gt;字符串(5)&#34;值&#34; }}

所以和预期的一样,但是如果它在所有情况下都适用,你应该在更普遍的使用之前测试它。如果找不到相同的密钥,则会得到false结果。