PHP:按索引值进行数组隔离

时间:2015-11-20 13:34:15

标签: php arrays

我有一个这样的数组:

[
        {
          "id": "13216",
          "image_type": "ThumbnailImage",
          "is_primary": "1"
        },
        {
          "id": "13217",
          "image_type": "MediumImage",
          "is_primary": "1"
        },
        {
          "id": "13218",
          "image_type": "LargeImage",
          "is_primary": "1"
        },
        {
          "id": "13219",
          "image_type": "ThumbnailImage",
          "is_primary": "0"
        },
        {
          "id": "13220",
          "image_type": "MediumImage",
          "is_primary": "0"
        },
        {
          "id": "13221",
          "image_type": "LargeImage",
          "is_primary": "0"
        }
]

我想把它转换成这个:

[
    "ThumbnailImage" => [
            {
                "id": "13216",
                "image_type": "ThumbnailImage",
                "is_primary": "1"
            },
            {
                "id": "13219",
                "image_type": "ThumbnailImage",
                "is_primary": "0"
            },
        ],
        "MediumImage" => [
            {
                "id": "13217",
                "image_type": "MediumImage",
                "is_primary": "1"
            },
            {
                "id": "13220",
                "image_type": "MediumImage",
                "is_primary": "0"
            },
        ],
        "LargeImage" => [
            {
                "id": "13218",
                "image_type": "LargeImage",
                "is_primary": "1"
            }, 
            {
                "id": "13221",
                "image_type": "LargeImage",
                "is_primary": "0"
            }
        ]
]

我正在寻找动态解决方案,我可以在其中指定密钥名称,并根据该索引的值自动隔离数组,例如在这种情况下,如果我指定索引名称image_type,它应该给我提到的输出,如果我指定is_primary,它应该返回索引0和1及其值。

最终解决方案:

public function segregateByIndex($array, $segregateKey)
{
        $result = [];
        foreach( $array as $val ) {
            $result[$val[$segregateKey]][] = $val;
        }
        return $result;
}

1 个答案:

答案 0 :(得分:3)

使用像{/ 1>这样的foreach非常容易解决

$result = [];
foreach(json_decode($your_json,true) as $key => $val){
    $result[$val['image_type']][] = $val;
}
print_r($result);