简体   繁体   English

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

[英]Get a specific recurring value from JSON array using PHP foreach loop

I have the following JSON array: 我有以下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"}

Using PHP is it possible to display a specific recurring value, for example if I wanted to display "key1" in a foreach loop it would return the following: 使用PHP可以显示特定的重复值,例如,如果我想在foreach循环中显示“ key1”,它将返回以下内容:

Example1
Example5
Example9

Appreciate any tips on what to use to do this, thanks. 感谢您使用此操作的任何提示,谢谢。

You aren't going to be able to do this using json_encode because it's not valid JSON. 您将无法使用json_encode进行此操作,因为它不是有效的JSON。 (Keyspace collision) (键空间冲突)

You are going to need to assemble the object manually. 您将需要手动组装对象。

You might consider creating the individual items, then using implode(). 您可以考虑创建单个项目,然后使用implode()。 Then you can prepend and append { and }. 然后,您可以在{和}之前和之后添加。

<?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']);

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM