2012-10-17 4 views
1

나는 이것이 매우 기본 적이어야한다는 것을 알고 있지만 이것을 해결하는 방법을 정말로 모른다. 자바 스크립트 스크립트 내에서 사용되는 다음 표기법으로 PHP 배열을 설정하고 싶습니다. 이것들은 초기화시에 js 스크립트에 전달되는 국가입니다. 내가 알아야 할 원하는대로 내가 원래 PHP 배열을 포맷 할 수 있습니다PHP 배열을 특정 Javascript 형식으로 변환하는 방법

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

소스 표기 (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)를 얻기 위해 포맷하는 방법입니다 원하는 결과. 내가 JS에 배열을 전달하려면 다음 코드를 사용하고

:

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

?> 

출력 :

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

답변

3

는 당신을 위해 일 것이다 다음과 같습니다

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

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

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

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

이 두 글자 코드를 각각 정상 1 차원 배열로 매핑 한 다음 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 
관련 문제