【问题标题】:mysql result is json array and i want to put array key in php variablemysql结果是json数组,我想把数组键放在php变量中
【发布时间】:2018-05-04 21:53:25
【问题描述】:

我的 mysql 结果是这样的 json 多维数组:

{'BrandTransactionItems': [
        {'ServiceCode':'PATROL_FIX','AbonentCode': 'ელ562705','Amount': 10.0
        },
        {'ServiceCode':'PATROL_FIX','AbonentCode': 'ელ606219','Amount': 10.0
        },
    ], 'BrandCode': 'jarima',   'Language': 'ge', 'ReturnUrl': 'http: //jarima.ge/'}

我只想从这个数组中获取 php 变量中的 Amount 值。如何?你能帮帮我吗?

【问题讨论】:

  • 如果那真的是你的字符串,它不是有效的 json。

标签: php mysql arrays json multidimensional-array


【解决方案1】:

您可以使用json_decode

$json = "{'BrandTransactionItems':[{'ServiceCode':'PATROL_FIX','AbonentCode': 'ელ562705','Amount': 10.0 },{'ServiceCode':'PATROL_FIX','AbonentCode': 'ელ606219','Amount': 10.0 },], 'BrandCode': 'jarima',   'Language': 'ge', 'ReturnUrl': 'http://jarima.ge/'}";
$array = json_decode($json);
foreach ($array['BrandTransactionItems'] as $key => $value) {
  if ($key == "Amount") {
    $result[] = $value;
  }
return $result;

$result 变量现在保存原始 JSON 中的每个“金额”值。

【讨论】:

  • 你不能使用json_decode(),因为字符串不是有效的json(它需要双引号而不是单引号)。
  • @jeroen 和一个逗号,后面没有对象。
  • @FirstOne 我什至没有走那么远:-)
  • 此代码返回此警告:为 foreach() 提供的参数无效......第 79 行是:foreach ($array['BrandTransactionItems'] as $key => $value) {跨度>
  • 对于此代码: $value) { if ($key == "Amount") { $result[] = $value; } 返回$结果; } ?> 是同样的错误:警告:为 PS 中的 foreach() 提供的参数无效 对于此示例 JSON 有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
相关资源
最近更新 更多