doushuo2834 2015-04-27 16:45
浏览 44
已采纳

PHP json string:获取关联数组对象

I have a json file with data like this (this is a partial view of the file to show structure):

{
"state": {
    "ALABAMA": {
        "ZOLD": [ "101", "102" ],
        "ZNEW": [ "11",  "12"  ]
    },
    "ALASKA": { 
        "ZOLD": [ "5001", "5002", "5003", "5004", "5005", "5006", "5007", "5008", "5009", "5010"],
        "ZNEW": [   "21",   "22",   "23",   "24",   "25",   "26",   "27",   "28",   "29",   "20"]
    }
}

}

What I want to do is search through it to find a value in the ZOLD field = $OLD, then return the value of the corresponding ZNEW array. I've tried going in with foreach and can get the arrays to echo out, but I'm not sure of what the value will be. Here's the code I have:

function translateZone($OLD)
{
$OLD = "5010";  //for testing purposes a constant but will be variable
$zStr  = file_get_contents('getnew.json');
$zJson = json_decode($zStr,true);
    foreach($zJson as $key=> $jsons)
    {
        foreach($jsons as $key=>$values)
        {
            foreach($values as $key=>$vals)
            {
                $counter=0;
                foreach($vals as $key=>$vls)
                {    
                    $counter ++;
                    echo var_dump($vls);//I can see the values,but now what?

                    if ($vls == $OLD)
                    {
                        $zTemp = Help here -some array value of counter??
                    }
                }
            }
            return $zTemp;
        }
}

I've searched through a bunch of other questions but haven't found something close enough to help with the problem.

Additional information: I may or may not know the "state" string (i.e. "Alaska") but I may want to return this information as well based on the found value.

Thanks for the help.

  • 写回答

2条回答 默认 最新

  • dongshanjin8947 2015-04-27 16:53
    关注

    Instead of trying to loop through ZOLD, you could use array_search (assuming that the $OLD value can only appear once in the data). This function will either return a number for the index of the value you search for or false if it cannot find it:

    $index = array_search($OLD,$values['ZOLD']);
    if ($index !== FALSE) {
        $zTemp = $values['ZNEW'][$index];
    }
    

    This would replace your two innermost for loop (as you need the other loops to get down to this level) and iterate through each state. At this point as well, $key would be defined to your state name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料