【问题标题】:How to fetch data from json string using php如何使用php从json字符串中获取数据
【发布时间】:2018-01-19 23:14:43
【问题描述】:

我有 json 字符串,我想从这个字符串中获取产品数据我该如何实现。请有人帮助我。

下面是我的字符串,

{"num_rows":2,"row":{"setting":"a:6:{s:4:\"name\";s:9:\"Featutred\";s:7:\"product\";a:2:{i:0;s:3:\"145\";i:1;s:3:\"148\";}s:5:\"limit\";s:1:\"5\";s:5:\"width\";s:3:\"200\";s:6:\"height\";s:3:\"200\";s:6:\"status\";s:1:\"1\";}"},"rows":[{"setting":"a:6:{s:4:\"name\";s:9:\"Featutred\";s:7:\"product\";a:2:{i:0;s:3:\"145\";i:1;s:3:\"148\";}s:5:\"limit\";s:1:\"5\";s:5:\"width\";s:3:\"200\";s:6:\"height\";s:3:\"200\";s:6:\"status\";s:1:\"1\";}"},{"setting":"a:6:{s:4:\"name\";s:17:\"Featured Products\";s:7:\"product\";a:2:{i:0;s:3:\"145\";i:1;s:3:\"146\";}s:5:\"limit\";s:1:\"4\";s:5:\"width\";s:3:\"200\";s:6:\"height\";s:3:\"200\";s:6:\"status\";s:1:\"1\";}"}]}

【问题讨论】:

  • json_decode 可以为您提供帮助
  • 但是您最终在 JSON 中使用了序列化 PHP,请重新考虑。
  • @MasivuyeCokile,不,不是。你甚至没有尝试解码它。

标签: php arrays json


【解决方案1】:

JSON 和 PHP 序列化数据混合在一起。

<?php
$string = '{"num_rows":2,"row":{"setting":"a:6:{s:4:\"name\";s:9:\"Featutred\";s:7:\"product\";a:2:{i:0;s:3:\"145\";i:1;s:3:\"148\";}s:5:\"limit\";s:1:\"5\";s:5:\"width\";s:3:\"200\";s:6:\"height\";s:3:\"200\";s:6:\"status\";s:1:\"1\";}"},"rows":[{"setting":"a:6:{s:4:\"name\";s:9:\"Featutred\";s:7:\"product\";a:2:{i:0;s:3:\"145\";i:1;s:3:\"148\";}s:5:\"limit\";s:1:\"5\";s:5:\"width\";s:3:\"200\";s:6:\"height\";s:3:\"200\";s:6:\"status\";s:1:\"1\";}"},{"setting":"a:6:{s:4:\"name\";s:17:\"Featured Products\";s:7:\"product\";a:2:{i:0;s:3:\"145\";i:1;s:3:\"146\";}s:5:\"limit\";s:1:\"4\";s:5:\"width\";s:3:\"200\";s:6:\"height\";s:3:\"200\";s:6:\"status\";s:1:\"1\";}"}]}';    

$dataObject = json_decode($string);
foreach($dataObject->rows as $row){

    $productData = unserialize($row->setting);
    print_r($productData);

}

会导致

Array
(
    [name] => Featutred
    [product] => Array
        (
            [0] => 145
            [1] => 148
        )

    [limit] => 5
    [width] => 200
    [height] => 200
    [status] => 1
)
Array
(
    [name] => Featured Products
    [product] => Array
        (
            [0] => 145
            [1] => 146
        )

    [limit] => 4
    [width] => 200
    [height] => 200
    [status] => 1
)

注意:上面的代码没有错误检查,因为它是为您的特定示例编写的。如果您不确定您的输入数据是否正确(通常情况下),您需要检查 JSON 是否正常、对象是否为对象以及是否具有所需的属性等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多