【问题标题】:PHP get JSON object value from Input array (array-like name)PHP 从输入数组中获取 JSON 对象值(类数组名称)
【发布时间】:2021-03-19 02:03:49
【问题描述】:

我有 3 个这样的输入:

<input type="text" name="product[1][name]" >
<input type="text" name="product[1][cost]" >
<input type="text" name="product[1][qty]"  >

...直到 n 个产品

<input type="text" name="product[n][name]" >
<input type="text" name="product[n][cost]" >
<input type="text" name="product[n][qty]"  >

并根据输入值生成如下 JSON 字符串:

{"product[1][name]": "Prod1", "product[1][cost]": "100$", "product[1][qty]": "3", "product[2][name]": "Prod2", ... }

我如何检索它们的名称和值,因为 json_decode 函数都不能获取它们的值,因为 类似数组的名称

$decodedObject=json_decode($array['data']); // this data contains the json string
echo $decodedObject->product; // does not work
echo $decodedObject->product[1][qty]; // does not work

有什么简单的方法吗? 还是唯一的办法就是像product[这样把名字剪掉,取里面的元素,:后面的值等等?

但是我如何才能在不让 PHP 知道它不是数组的情况下从中获取对象呢?

【问题讨论】:

  • 你是如何创建 JSON 的?
  • @El_Vanja JSON 是从表单创建的,每个表单输入都被获取并转换为 JSON 字符串,然后上传到数据库中。我想从我将从数据库中获取的 JSON 字符串中检索“product[x][name]”。
  • 您使用哪个 REQUEST 参数来获取表单值?我认为您最好将该数组处理为适当的 JSON 对象并将其存储在数据库中以供以后检索。
  • @Alex.Barylski 我将表单数据发送到 AJAX 脚本,该脚本将其作为 VARCHAR 数据类型插入数据库,如果这是问题的话:)
  • @Lepy 为什么要把它变成 JSON 然后发送到服务器?为什么不直接发布 HTML 表单?

标签: php arrays json string


【解决方案1】:

首先我找到了一个替代方案。问题在于:

$decodedObject=json_decode($array['data']); // will create an object

不会将其转换为数组,而是我使用了这个:

$decodedObject=json_decode($array['data'], true); // will create an array 

之后我检查了存在多少对象,然后将它们添加到另一个数组中:

$i=1;
while(isset($decodedObject["product[$i][qty]"])) // while any element exists
{
    $newProducs= array();
    $newProducs['name'] = $decodedObject["product[$i][name]"];
    $newProducs['cost'] = $decodedObject["product[$i][cost]"];
    $newProducs['qty'] = $decodedObject["product[$i][qty]"];
    array_push($products, $newProducs); // optional: add to the main array (products) the new-created array (newProducs)
    $i++; //increment to search another product
}

问题是我没有完全创建一个数组 -_-

虽然这不是完整的答案,但我仍然希望有人能找到更好的解决方案而不是改变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2011-10-27
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多