3

In php the response I am getting looks like this:

{
    "GB": "United Kingdom",
    "US": "United States"
}

I need something I can loop over using map like this

   [
    { code: "GB", name: "United Kingdom" },
    { code: "US", name: "United States" },
   ]

But I would like to use PHP to convert this into an array of objects. Can it be done with PHP or only Javascript?

function get_billing_countries( $request ) {
 
    $woo_countries = new WC_Countries();
    $countries = $woo_countries->get_allowed_countries();
    
    return $countries;
    
}
0

4 Answers 4

3

This can be done either in php or Js, If you want to do it in php before passing to to client side

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

You can also take the similar approach in Js on client side

If response in Js is as below

const responseCountries = {
    "GB": "United Kingdom",
    "US": "United States"
}
const countries = []
for(const property in responseCountries){
   countries.push({code: property, name: responseCountries[property]})
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is looking great so far, except that the php version seems to be escaping or putting slashes everywhere `[{\"code\":\"UK`
i think that's expected, I think you can just return $arrayCountries without json_encode if you are using wp rest
0

You can do (array)$yourArray to achieve this.

EDIT

A single object converted into an array of objects (of a single element) looks like this:

[$yourArray]

3 Comments

Thank you, I have edited my question to provide more detail.
@Waterfall please check my edited answer where I address your question in the comment.
I have tied this (not sure if correct) $test = (array)[$countries]; return $test; but that returns [{ "GB": "United Kingdom", "US": "United States" }] so the objects are still in one instead of split up like my example.
0

Suppose we have these objects and wants to convert to another type. json to array and array to json.

$array = ['ali' => 110, 'reza' => 20];

$json = '{"ali": 110, "reza": 20}';

array to json:

$json_result = json_encode($array);

json to array:

$array_result = json_decode($json);

Comments

0

You can use the json_decode($yourArray) function. It can be used to convert JSON to PHP arrays.

Let me explain (I won't be mad like some other people, even though I found an answer in 30 seconds):

You can type a script and add the JSON object in there. Then, you will set a cookie to the object stringified:

<script>
    var json = {"one":1, "two":2};
    var jsonStr = JSON.stringify(json);
    document.cookie("json="+jsonStr);
</script>

No matter how you ended up with the JSON object, you can do this in any way. Then, you dump it in PHP, if the cookie is set. Else, reload the page so that the cookie is set:

<?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
?>

Output:

array(2) { ["one"]=> int(1) ["two"]=> int(2) }

This would solve the first version of your question, but you changed it and wanted an array of split objects. Like this:

{
"one":1,
"two":2
}

To be converted to this:

[
{"one":1},
{"two":1}
]

I would ask why, but let me just solve this.

Remember the script we wrote? Let's add more to it.

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

So what exactly does this function do? For each key of the object, it pushes it into the array. Keep your PHP the same.

2 Comments

Thank you for this, however it doesn't look like your output matches the one I have shown.
I updated it. It should solve your problem by now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.