dpj96988 2016-12-07 07:42
浏览 226
已采纳

使用php在JSON中搜索值

I have a JSON file in this format:

[
 ["name","purpose","description"],
 ["name2","purpose2","description2"],
 ["name3","purpose3","description3"]
]

Now, I have got the solutions for finding them by key. But, my JSON doesn't have keys. How can I search inside this JSON object to find second element by using "purpose2"? Also, I need to display the second element (i.e. "name2","purpose2","description2").

I used this function, but it's not helping me out.

function searchJson($obj, $value) {
foreach($obj as $item) {
    foreach($item as $child) {
        if(isset($child) && $child == $value) {
            return $child;
        }
    }
}
return null;
}

Thanks in advance !

  • 写回答

1条回答 默认 最新

  • duanju6788 2016-12-07 07:56
    关注

    As the json data doesn't have string keys upon which to search you can branch the logic in the function to test for numeric indexes and then use in_array perhaps

    $json = '[["name","purpose","description"],["name2","purpose2","description2"],["name3","purpose3","description3"]]';
    
    function searchJson( $obj, $value ) {
        foreach( $obj as $key => $item ) {
            if( !is_nan( intval( $key ) ) && is_array( $item ) ){
                if( in_array( $value, $item ) ) return $item;
            } else {
                foreach( $item as $child ) {
                    if(isset($child) && $child == $value) {
                        return $child;
                    }
                }
            }
        }
        return null;
    }
    $data = json_decode( $json );
    $results = searchJson( $data , 'purpose2' );
    print_r( $results );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样