【问题标题】:Converting Javascript Object into PHP array [duplicate]将Javascript对象转换为PHP数组[重复]
【发布时间】:2018-03-18 23:38:40
【问题描述】:

我使用表单提交 {"1":"2","2":"2","3":"2","4":"2"} 将此 Javascript 数组发送到 PHP 页面

现在,我想把这个数组转换成 PHP 数组,像这样

$cars = array("Volvo", "BMW", "Toyota");

所以,这就是我尝试过的:

$phparray = str_replace(':', ',', $_POST["questionandanswers"]); // Remove : and replace it with ,
$phparray = str_replace('}', '', $phparray); // Remove }
$phparray = str_replace('{', '', $phparray); // Remove {
echo '<br/>';
echo $phparray; // Output of this is: "1","2","2","2","3","2","4","2"



$questionandanswers = array($phparray); // Now convert it into PHP array

但它不起作用。看起来我不能把$phparray 变量放在这里array($phparray)

但是,如果不是将$phparray 变量放入array($phparray),而是手动将$phparray 的输出放入,那么它的工作方式类似于:array("1","2","2","2","3","2","4","2")

解决办法是什么?

【问题讨论】:

  • 这不是“Javascript 数组”,而是JSON
  • json_decode($json)

标签: javascript php arrays


【解决方案1】:

您的表单似乎向服务器提交了一个 json 对象,因此请使用 json_decode 并将第二个参数设置为 true 将其转换为数组

$php_array=  json_decode($_POST["questionandanswers"],true)

【讨论】:

  • 谢谢,但这里的问题是,对象名称并不总是按顺序排列:它也可以像Array ( [3] =&gt; 0 [6] =&gt; 0 [7] =&gt; 0 [11] =&gt; 0 ) 。那么,如何在不知道对象名称的情况下访问对象呢?
  • 根据您的情况使用带有 if 语句的 foreach 循环。
  • 顺便说一句,你拼错了 json_decode
【解决方案2】:

json_decode($json) 一样使用json_decode。它将返回一个对象。 如果你想要数组,使用json_decode($json, true)。 见:http://sg2.php.net/manual/en/function.json-decode.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多