根据键json decode和foreach在一行中提取值

时间:2015-05-06 11:02:56

标签: php arrays json foreach

我需要弄清楚如何让showBtn(3)与其他每个键的第一个结果相匹配。

ShowBtn/3 
btnMenulink/101 
btnArticleLink/2 
btnPhone/036244789 
btnUrl/ 
btnName/Office

PHP:

$jsonresult = '{"showBtn":["3","3"],"btnMenuLink":["101","101"],"btnArticleLink":["2","2"],"btnPhone":["036244789","0404256478"],"btnURL":["",""],"btnName":["Office","Mobile"]}';

$array      = json_decode($jsonresult,true);

foreach ($array as $key => $value) {
    foreach ($value as $next_key => $next_value) { 
        echo $key . ":" . $next_key . ":" . $next_value . "\n";
    }
}

我想要这个:

if (showBtn == 3) {

    echo '<a href='tel:btnPhone'>btnName</a>';

}

结果将是

<a href="tel:036244789">Office</a> <a href="tel:0404256478">Mobile</a>

我几乎拥有它!

$jsonresult = '{"showBtn":["3","3"],"btnMenuLink":["101","101"],"btnArticleLink":["2","2"],"btnPhone":["036244789","0404256478"],"btnURL":["",""],"btnName":["Office","Mobile"]}';

$parsed     = json_decode($jsonresult,true);

echo 'Showbtn: '.$parsed['showBtn'][0].' Phone: '.$parsed['btnPhone'][0].' Name: '.$parsed['btnName'][0];
echo '<hr/>Showbtn: '.$parsed['showBtn'][1].' Phone: '.$parsed['btnPhone'][1].' Name: '.$parsed['btnName'][1];

现在我必须以某种方式将[0] [1]放入循环中

我有它但可以做得更好吗?

$jsonresult = '{"showBtn":["3","3"],"btnMenuLink":["101","101"],"btnArticleLink":["2","2"],"btnPhone":["036244789","0404256478"],"btnURL":["",""],"btnName":["Office","Mobile"]}';

$parsed          =   json_decode($jsonresult,true);

$i=0;

foreach ($parsed as $key => $value) {

    if ($parsed['showBtn'][$i] == 3) {

       echo 'Showbtn: '.$parsed['showBtn'][$i].' Phone: '.$parsed['btnPhone'][$i].' Name: '.$parsed['btnName'][$i].'<hr/>';   

    }
    $i++;  
}

1 个答案:

答案 0 :(得分:1)

这对你有用。你需要以这种方式工作

$jsonresult = '{"showBtn":["3","3"],"btnMenuLink":["101","101"],"btnArticleLink":["2","2"],"btnPhone":["036244789","0404256478"],"btnURL":["",""],"btnName":["Office","Mobile"]}';

$array = json_decode($jsonresult,true);

foreach($array['showBtn'] as $key => $value){   
    if($value == 3){
        echo '<a href="tel:'.$array['btnPhone'][$key].'">'.$array['btnName'][$key].'</a><br>';
    }
}

输出:

Office
Mobile