duanfa0072 2016-10-12 01:18
浏览 62

JSON格式化为字符串,转换为php数组?

I have a JSON string which is stored in a MYSQL DB. Example:

stdClass Object (
[product] => stdClass Object
    (
        [sold_individually] => 
        [regular_price] => 
        [managing_stock] => 1
        [sku] => 0001
        [title] => Sample title
        [reviews_allowed] => 1...

etc.

I have used utf8_encode() to convert it. How can I then turn this in to a PHP array so I can use it?

Edit 1

I have now used json_encode() when posting to the DB. I have also had to use addSlashes() as I was getting some formatting issues with some of the values.

When I now pull in the data it looks like:

"{\"product\": {\"sold_individually\": false, \"regular_price\": \"\", \"managing_stock\": true, \"sku\": \"W-C-6500\", \"title\": \"Sample title\"...

How can I pull out the value for "title"? Should I also use str_replace() to get rid of the \ issue?

  • 写回答

3条回答 默认 最新

  • douwen9343 2016-10-12 01:38
    关注

    What you printed is not JSON, it's the string representation of a php Object I think. So if possible, you should store into your database actual JSON. It's easier, cleaner and more compact.

    To do so, use json_encode($your_object) to insert the data in your database.

    To retrieve it, use json_decode($string_from_database).

    This should work like a charm.

    Note: There's a trap though, by default, json_decode will create a php Object and not an array. So you have to retrieve your fields as attributes of an object:

    $data = json_decode($string_from_database);
    $data->product->title; // to access title in your data structure
    

    But if you want an array, you can provide an argument to get an array and then it works like this:

    $data = json_decode($string_from_database, true);
    $data['product']['title']; // to access title in your data structure
    

    Check the php documentation of json_decode for further info!

    http://php.net/manual/fr/function.json-decode.php

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP