2012-10-17 44 views
1

我知道这一定是非常基本的,但我真的不知道如何解决这个问题。我想将一个php数组转换为以下符号用于JavaScript脚本中。这些是在初始化时传递给js脚本的国家。如何将PHP数组转换为特定的Javascript格式

源符号(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>"; 

回答

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来工作。

0

array_reduce状况:

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

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

}, array()); 

echo json_encode($output); 
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 
相关问题