0

我如何从这个 json 创建一个将 ATTRIBUTE_TYPE 关联到 ATTRIBUTE ID 的数组。现在我被返回以下json:

(
    [success] => 1
    [ATTRIBUTES_COUNT] => 106
    [ATTRIBUTES] => Array
        (
            [0] => Array
                (
                    [ATTRIBUTE_TYPE] => email
                    [DATA_TYPE] => CHAR
                    [COMPARE_COUNT] => 2
                    [COMPARE] => Array
                        (
                            [0] => Array
                                (

                                    [ATTRIBUTE_ID] => 4222
                                    [DESCR] => Equals
                                )

                            [1] => Array
                                (

                                    [ATTRIBUTE_ID] => 4223
                                    [DESCR] => Not Equal
                                )

                        )

                )

            [1] => Array
                (
                    [ATTRIBUTE_TYPE] => interest
                    [DATA_TYPE] => MONEY
                    [COMPARE_COUNT] => 7
                    [COMPARE] => Array
                        (
                            [0] => Array
                                (

                                    [ATTRIBUTE_ID] => 4006
                                    [COMPARE_DESCR] => Not Equal
                                )

                            [1] => Array
                                (

                                    [ATTRIBUTE_ID] => 4000
                                    [COMPARE_DESCR] => Equals
                                )

                            [2] => Array
                                (

                                    [ATTRIBUTE_ID] => 4001
                                    [COMPARE_DESCR] => Greater Than
                                )

                       )

                )
)

现在我想创建一个数组,它会在 json_decode 之后返回如下内容:

{
    "DETAILS": [
        {

            "ATTRIBUTE_ID": "4222",
            "ATTRIBUTE_TYPE": "email",

        },
        {

            "ATTRIBUTE_ID": "4006",
            "ATTRIBUTE_TYPE": "interest",


        }
    ]
}

同一个属性类型可以有多个属性ID。

4

1 回答 1

1

它不是特别优雅,但试一试($inputArray 是您在问题顶部发布的深度嵌套数组):

$desiredArray = array("DETAILS" => array());

foreach($inputArray["ATTRIBUTES"] as $attribute)
{
    foreach($attribute["COMPARE"] as $compare)
    {
        $desiredArray["DETAILS"][] = array("ATTRIBUTE_ID" => $compare["ATTRIBUTE_ID"],
            "ATTRIBUTE_TYPE" => $attribute["ATTRIBUTE_TYPE"]);
    }
}

$desiredJson = json_encode($desiredArray);
于 2012-09-18T20:56:11.513 回答