doumowu7371 2018-08-11 05:56
浏览 169
已采纳

循环遍历json文件以在PHP中查找特定值

My json file look likes

myjson.json

[
{"name":"category_01","data":
[
{"id":"1","word":"ma","given_value":"1"},
{"id":"3","word":"me","given_value":"1"},
] }
[
{"name":"category_02","data":
[
{"id":"1","word":"vea","given_value":"1"},
{"id":"3","word":"ve","given_value":"1"},
] }

So what I want here is, check whether a particular value is in this json array using php. Assume that,

myphp.php

$word = 've';

if this value is in the above array, should find is it in category_01 or category_02. and also want to find given_value of matching word. I just tried in this way,

$data = file_get_contents ("myjson.json");
$json = json_decode($data, true);

foreach($arr as $item) { 
$uses = ($item['word']= $word); 
}

This doesn't work. How can I fix this, Please help me!

  • 写回答

1条回答 默认 最新

  • douduan6731 2018-08-11 06:11
    关注

    First of all, the JSON you posted is invalid. I think it should look like this:

    [
        {
            "name": "category_01",
            "data": [{
                    "id": "1",
                    "word": "ma",
                    "given_value": "1"
                },
                {
                    "id": "3",
                    "word": "me",
                    "given_value": "1"
                }
            ]
        },
        {
            "name": "category_02",
            "data": [{
                    "id": "1",
                    "word": "vea",
                    "given_value": "1"
                },
                {
                    "id": "3",
                    "word": "ve",
                    "given_value": "1"
                }
            ]
        }
    ]
    

    Try using on online tool like https://jsonlint.com/ to check your JSON. (if you get errors i recommend build the json again from scratch).

    I also recommend checking your json before using it:

    if ($arr === null && json_last_error() !== JSON_ERROR_NONE) {
        die("incorrect json data");
    }
    

    To get your value you have to KNOW how your data looks like and then process it:

    foreach($arr as $category) { 
        foreach($category['data'] as $data) { 
            if(strstr($data['word'], $word))
            echo $category['name'].' '.$data['word'].' '.$data['given_value']."
    ";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示