使用PHP foreach循环从JSON数组中获取特定的重复值

时间:2015-09-21 10:48:32

标签: php arrays json foreach

我有以下JSON数组:

{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}

使用PHP可以显示特定的重复值,例如,如果我想在foreach循环中显示“key1”,它将返回以下内容:

Example1
Example5
Example9

感谢有关使用该功能的任何提示,谢谢。

1 个答案:

答案 0 :(得分:2)

您无法使用json_encode执行此操作,因为它无效JSON。 (Keyspace碰撞)

您需要手动组装对象。

您可以考虑创建单个项目,然后使用implode()。然后你可以在前面添加{和}。

<?php
$jsonObject='{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}';

$jsonArray = array_map(
    function($array){
    $keyValue=explode(":",$array);
    return array("key"=>substr($keyValue[0],1,-1),"value"=>substr($keyValue[1],1,-1));

    },
    explode(
        ",",
        substr($jsonObject,1,-1)

    )
);

foreach($jsonArray as $object){
    $output[$object['key']][]=$object['value']; 
}
echo implode("\n",$output['key1']);

?>