【问题标题】:Search through JSON to build MySQL Insert?通过 JSON 搜索构建 MySQL 插入?
【发布时间】:2013-07-12 20:20:08
【问题描述】:

我正在尝试在我的网站上集成 OpenID 登录系统。我已经使用了提供的代码,登录系统确实正确返回了我的数据,并且它已成功存储在 PHP 中。

从 OpenID 返回的数据:

Array
(
    [family_name] => Doe
    [name] => John Doe
    [account_type] => BUSINESS
    [given_name] => John
    [address] => Array
        (
            [postal_code] => 12345
            [locality] => Test
            [region] => NE
            [country] => US
            [street_address] => 123 Main Street
        )

    [verified_account] => true
    [language] => en_US
    [zoneinfo] => America/Chicago
    [locale] => en_US
    [phone_number] => 5553891234
    [email] => johndoe@test.com
    [account_creation_date] => 2008-03-06
    [birthday] => 2000-01-01
    [age_range] => 18-25
) 

然后,我使用 var_dump 将 JSON 转换为数组。

打印var_dump后的数据时,我的数据如下:

array(14) { ["family_name"]=> string(9) "Doe" ["name"]=> string(13) "John Doe" ["account_type"]=> string(8) "BUSINESS" ["given_name"]=> string(3) "John" ["address"]=> array(5) { ["postal_code"]=> string(5) "12345" ["locality"]=> string(5) "Test" ["region"]=> string(2) "NE" ["country"]=> string(2) "US" ["street_address"]=> string(32) "123 Main Street" } ["verified_account"]=> string(4) "true" ["language"]=> string(5) "en_US" ["zoneinfo"]=> string(15) "America/Chicago" ["locale"]=> string(5) "en_US" ["phone_number"]=> string(10) "5553891234" ["email"]=> string(20) "johndoe@test.com" ["account_creation_date"]=> string(10) "2008-03-06" ["birthday"]=> string(10) "2000-01-01" ["age_range"]=> string(5) "18-25" }

现在我的问题变成了(这就是我卡住的地方)我如何循环遍历数组并只提取数据?我正在尝试从创建用户帐户的数据中构建 MySQL 插入。

我宁愿不只是假设用户的姓氏将是存储在数组中的第一件事。有没有办法轻松搜索数组并只返回数据?

我查看了 print_r 和其他一些方法,但似乎一切都返回 ["family_name"]=> string(9) "Doe" 而不仅仅是 Doe

【问题讨论】:

  • 从json中,用$myArray = json_decode($jsonData, true);创建一个数组,然后用$name = $myArray['family_name'];访问数据

标签: php mysql arrays openid var-dump


【解决方案1】:

如果您有 JSON 字符串,您可以使用 json_decode() 将其转换为数组。然后,您可以使用常规数组语法获取任何属性的值..

例如。

$user_info = json_decode($json_string, true);
$family_name = $user_info["family_name"]

【讨论】:

  • 这样,它不会工作,因为json_decode 默认返回stdClass。要使其成为数组,请使用json_decode($json, true);,因为true 将使返回改为关联数组。 ^^
  • 感谢大家的回答。现在正在着手实施。 :)
猜你喜欢
  • 1970-01-01
  • 2019-09-12
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多