如何将具有键值对的对象转换为对象数组

3
在php中,我得到的响应看起来像这样:
{
    "GB": "United Kingdom",
    "US": "United States"
}

我需要一个类似于这样使用 map 进行循环的东西。
   [
    { 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;
    
}
4个回答

3
这可以在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
到目前为止看起来很不错,除了PHP版本似乎在任何地方都转义或添加斜杠 [{\"code\":\"UK\ - Waterfall
我认为这是可以预料的,如果您正在使用wp rest,则可以只返回$arrayCountries而无需json_encode。 - Yalamber

0

您可以使用(array)$yourArray来实现此操作。

编辑

将单个对象转换为仅包含一个元素的对象数组,代码如下:

[$yourArray]

谢谢,我已经编辑了我的问题以提供更多细节。 - Waterfall
@Waterfall,请检查我的编辑答案,在评论中回答了你的问题。 - Lajos Arpad
我尝试过这个代码(不确定是否正确)$test = (array)[$countries]; return $test;,但是它返回了[{ "GB": "United Kingdom", "US": "United States" }],所以对象仍然在一个数组中,而不是像我的示例那样分开。 - Waterfall

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不变。


谢谢你的回复,不过看起来你的输出结果和我展示的不太一样。 - Waterfall
我已经更新了。现在应该解决你的问题了。 - Ath.Bar.

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接