1

I know this must be very basic but I really don't know how to solve this. I want to turn a php array to the following notation to be used inside a javascript script. These are countries which are passed to the js script in the initialization.

Source notation (PHP)

array(3) { [0]=> array(1) { ["code"]=> string(2) "AR" } [1]=> array(1) { ["code"]=> string(2) "CO" } [2]=> array(1) { ["code"]=> string(2) "BR" } }

Desired outcome (JS)

[ "AR", "FK","CO", "BO", "BR", "CL", "CR", "EC", "GT", "HN", "LT", "MX", "PA", "PY", "PE", "ZA", "UY", "VE"]

I can reformat the origin PHP array as desired, what I need to know is how to format it to get the desired outcome.

I am using the following code to pass the array to js:

echo "<script>var codes = " . json_encode($codes) . ";</script>";

3 Answers 3

3

Looks like the following would work for you:

<?php

$arr[0]['code'] = 'AR';
$arr[1]['code'] = 'CO';
$arr[2]['code'] = 'BR';

print_r($arr);


function extract_codes($var) { return $var['code']; }

print_r(array_map('extract_codes', $arr));

echo json_encode(array_map('extract_codes', $arr));

?>

Output:

Array
(
    [0] => Array
        (
            [code] => AR
        )

    [1] => Array
        (
            [code] => CO
        )

    [2] => Array
        (
            [code] => BR
        )

)
Array
(
    [0] => AR
    [1] => CO
    [2] => BR
)
["AR","CO","BR"]

It works by mapping each of the two-letter codes down to a normal one-dimensional array, then passing it to json_encode.

0

Going with array_reduce:

$output = array_reduce($array, function($result, $item){

    $result[] = $item['code'];
    return $result;

}, array());

echo json_encode($output);
0

You need to loop through your PHP associative array and set the appropriate variables. Like this:

$item = ''; // Prevent empty variable warning
foreach ($php_array as $key => $value){
  if (isset($key) && isset($value)) { // Check to see if the values are set
    if ($key == "code"){ $item .= "'".$value."',"; } // Set the correct variable & structure the items
  }
}
$output = substr($item,'',-1); // Remove the last character (comma)
$js_array = "[".$output."]"; // Embed the output in the js array
$code = $js_array; //The final product

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.