在 php 中,我得到的响应如下所示:
{
"GB": "United Kingdom",
"US": "United States"
}
我需要一些可以使用这样的地图循环的东西
[
{ code: "GB", name: "United Kingdom" },
{ code: "US", name: "United States" },
]
但我想使用 PHP 将其转换为对象数组。可以用 PHP 还是只用 Javascript 来完成?
function get_billing_countries( $request ) {
$woo_countries = new WC_Countries();
$countries = $woo_countries->get_allowed_countries();
return $countries;
}
答案 0 :(得分:1)
这可以在 php 或 Js 中完成, 如果您想在传递给客户端之前在 php 中执行此操作
function get_billing_countries( $request ) {
$woo_countries = new WC_Countries();
$countries = $woo_countries->get_allowed_countries();
$arrayCountries = [];
foreach($countries as $key=>$val){
$arrayCountries[] = ["code" => $key, "name" => $val];
}
return json_encode($arrayCountries);
}
您也可以在客户端的 Js 中采用类似的方法
如果 Js 中的响应如下
const responseCountries = {
"GB": "United Kingdom",
"US": "United States"
}
const countries = []
for(const property in responseCountries){
countries.push({code: property, name: responseCountries[property]})
}
答案 1 :(得分:0)
您可以执行 (array)$yourArray
来实现这一目标。
编辑
转换为对象数组(单个元素的)的单个对象如下所示:
[$yourArray]
答案 2 :(得分:0)
您可以使用 json_decode($yourArray)
函数。可用于将 JSON 转换为 PHP 数组。
让我解释一下(我不会像其他人一样生气,即使我在 30 秒内找到了答案):
您可以键入脚本并在其中添加 JSON 对象。然后,您将为字符串化的对象设置一个 cookie:
<script>
var json = {"one":1, "two":2};
var jsonStr = JSON.stringify(json);
document.cookie("json="+jsonStr);
</script>
无论您最终如何获得 JSON 对象,您都可以以任何方式执行此操作。 然后,如果设置了 cookie,则将其转储到 PHP 中。否则,重新加载页面以设置 cookie:
<?php
if (!isset($_COOKIE["json"])){
//Check whether the cookie is set. If not so, then reload the document:
echo "<script>location.reload();</script>";
exit; //Exit is because you don't want actions in PHP to continue after the page has been set to be reloaded
}
else{
//But, if the cookie is set, then set a variable to it
$json = $_COOKIE["json"];
}
$decoded = json_decode($json, true); //Decode the object. You should type "true" because else it will be converted to an std_class... I didn't search any more on this
var_dump($decoded); //See the output
?>
输出:
array(2) { ["one"]=> int(1) ["two"]=> int(2) }
这将解决您问题的第一个版本,但您更改了它并想要一个拆分对象数组。像这样:
{
"one":1,
"two":2
}
要转换成这样:
[
{"one":1},
{"two":1}
]
我会问为什么,但让我解决这个问题。
还记得我们写的脚本吗?让我们添加更多。
<script>
//Now you wanted for each key on the object to be added into an array. I made a function for this:
function objectToArray(object){
var retArray = [];
var allKeys = Object.keys(object);
for (i = 0; i < allKeys.length; i++){
//For each key of the object:
toBeAdded = allKeys[i];
toBeAddedObj = {};
toBeAddedObj[toBeAdded] = object[toBeAdded];
retArray.push(toBeAddedObj);
}
return retArray;
}
var json = {"one":1, "two":2};
json = objectToArray(json);
var jsonStr = JSON.stringify(json);
document.cookie("json="+jsonStr);
</script>
那么这个函数到底是做什么的呢?对于对象的每个键,它将其推入数组。保持您的 PHP 不变。
答案 3 :(得分:0)
假设我们有这些对象并且想要转换为另一种类型。 json 到数组,数组到 json。
$array = ['ali' => 110, 'reza' => 20];
$json = '{"ali": 110, "reza": 20}';
数组到json:
$json_result = json_encode($array);
json 到数组:
$array_result = json_decode($json);