【问题标题】:Python object output to PHP ArrayPython 对象输出到 PHP 数组
【发布时间】:2018-05-25 11:37:51
【问题描述】:

看完相关问题,这里不得不提一下我的问题。

我正在运行一个 python 脚本来从 Google place API 获取数据。以某种方式使用 PHP 进行管理,我将对象列表转换为以下输出:

[   {
    'fri_hours': "b'9:00 AM \\xe2\\x80\\x93 8:00 PM'",
    'wed_hours': "b'9:00 AM \\xe2\\x80\\x93 8:00 PM'",
    'sun_hours': "b'Closed'",
    'photo_reference': '',
    'phone_number': b'+1 212-354-1006',
    'state': b'New York',
    'country': b'United States',
    'place_id': 'ChIJ8cFYDKpZwokRpC04mEYm20s',
    'thu_hours': "b'9:00 AM \\xe2\\x80\\x93 8:00 PM'",
    'business_name': b'CarLeo Hair Salon',
    'address': b'22West 38th Street',
    'city': b'New York',
    'mon_hours': "b'9:00 AM \\xe2\\x80\\x93 6:00 PM'",
    'type': 'beauty salon',
    'sat_hours': "b'Closed'",
    'tue_hours': "b'9:00 AM \\xe2\\x80\\x93 8:00 PM'",
    'postal_code': '10018',
    'website': 'http://www.carleohairsalon.com/',
    'rating': 4.6   } ][   {
    'fri_hours': "b'8:00 AM \\xe2\\x80\\x93 8:00 PM'",
    'wed_hours': "b'8:00 AM \\xe2\\x80\\x93 8:00 PM'",
    'sun_hours': "b'Closed'",
    'photo_reference': 'CmRaAAAAe8XIMwcPu3uhohYjJ-dQt69rtZ-x2XJ-I28USF-LphSaVH4Gt-_JUmB06TGnOKKmAqSjnhGuFqUKb7pitV1twViGVE7znVYLSdRYZ72LKjtlXT47YapfEreCmd9lK1R8EhCEJ2Pb2Fpe2sbfbOF3hXgmGhRaJbdZKiF8S0GxdzVj3r7mQphVtw',
    'phone_number': b'+1 212-688-6498',
    'state': b'New York',
    'country': b'United States',
    'place_id': 'ChIJ0SFDYuVYwokRXJvyfmR9kec',
    'thu_hours': "b'8:00 AM \\xe2\\x80\\x93 8:00 PM'",
    'business_name': b'Mizu Salon',
    'address': b'505Park Avenue',
    'city': b'New York',
    'mon_hours': "b'10:00 AM \\xe2\\x80\\x93 6:00 PM'",
    'type': 'beauty salon',
    'sat_hours': "b'9:00 AM \\xe2\\x80\\x93 7:00 PM'",
    'tue_hours': "b'8:00 AM \\xe2\\x80\\x93 7:00 PM'",
    'postal_code': '10022',
    'website': 'http://www.mizuforhair.com/',
    'rating': 4.4   } ]

现在,我只是想使用 PHP 将上述输出转换为包含对象子数组的单个数组

我尝试过使用 foreach 循环,但得到了相同的输出。

【问题讨论】:

  • 您是否尝试将您的列表转换为 json?在 php 中你可以比json_decode 的内容,你应该有你的数组
  • 已经尝试过但获取单个对象的列表所以没有帮助

标签: php arrays object


【解决方案1】:

在您的 python 脚本中执行类似的操作

import json
#some code here
jsonStr = json.dumps(myListFromGooglePlaces)
#whatever you do to get it to php

然后正如我在上面的评论中提到的那样

$arr = json_decode($json, true);

我希望这对你有用。

【讨论】:

  • 试过这个并得到json不可序列化的错误
  • 你用的是什么python版本?
  • 你好 Domenik,我使用的是 Python 3.5.2
  • 你能在编码之前打印你的列表(你从你的 API 调用中得到什么)并在这里发布吗?
  • 如果您确实有一个列表,那么该代码将起作用。所以还要打印变量的类型
【解决方案2】:

你可以使用 json_decode 函数

j_obj = '[{ ....}]';

$array = json_decode($j_obj,true);

【讨论】:

  • 我在单个数组中获取每个对象,这也是问题之一
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-20
  • 2014-08-11
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多