我知道这一定是非常基本但我真的不知道如何解决这个问题。我想将一个php数组转换为以下符号,以便在javascript脚本中使用。这些是在初始化中传递给js脚本的国家。
源代码(PHP)
array(3) { [0]=> array(1) { ["code"]=> string(2) "AR" } [1]=> array(1) { ["code"]=> string(2) "CO" } [2]=> array(1) { ["code"]=> string(2) "BR" } }
期望的结果(JS)
[ "AR", "FK","CO", "BO", "BR", "CL", "CR", "EC", "GT", "HN", "LT", "MX", "PA", "PY", "PE", "ZA", "UY", "VE"]
我可以根据需要重新格式化原始PHP数组,我需要知道的是如何格式化它以获得所需的结果。
我使用以下代码将数组传递给js:
echo "<script>var codes = " . json_encode($codes) . ";</script>";
答案 0 :(得分:3)
以下内容适用于您:
<?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));
?>
输出:
Array
(
[0] => Array
(
[code] => AR
)
[1] => Array
(
[code] => CO
)
[2] => Array
(
[code] => BR
)
)
Array
(
[0] => AR
[1] => CO
[2] => BR
)
["AR","CO","BR"]
它的工作原理是将每个双字母代码映射到一个普通的一维数组,然后将其传递给json_encode。
答案 1 :(得分:0)
使用array_reduce
:
$output = array_reduce($array, function($result, $item){
$result[] = $item['code'];
return $result;
}, array());
echo json_encode($output);
答案 2 :(得分:0)
您需要遍历PHP关联数组并设置适当的变量。 像这样:
$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