douwen9540 2017-09-17 18:55
浏览 52
已采纳

具有指定标签的PHP Json值

I am using json_decode and echoing the values using a nested foreach loop.

Here's a truncated json that I am working on:

[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"},....

and the loop

foreach($list_array as $p){
    foreach($p as $key=>$value) {
        $result_html .= $key.": ".$value."<br />";
    }
}

This was I am able to echo all key/value pairs.

I have tried using this to echo individual items something like:

foreach($list_array as $p){
    foreach($p as $key=>$value) {
        echo "Product: ".$p[$key]['product_name'];
        echo "Quantity: ".$p[$key]['product_quantity'];
    }
}

However I am unable to because it doesn't echo anything.

I would like to be able to show something like:

Product Name: Apple

Quantity: 7

Currently it is showing:

product_name: Apple

product_quantity: 7

How can I remove the key and replace it with a predefined label.

  • 写回答

2条回答 默认 最新

  • dongxiang7276 2017-09-17 19:18
    关注

    If you are decoding your json into an object you can do it like that.

    $list_array = json_decode('[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"}]');
    
    $result_html = '';
    foreach($list_array as $p){
        $result_html .= '<div>Product: '.$p->product_name.'</div>';
        $result_html .= '<div>Quantity: '.$p->product_quantity.'</div>';
    }
    echo $result_html;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了