[英]PHP / JS: convert PHP array to JavaScript array
我有一個PHP數組( $cloud
),在使用json_encode
,當我打印它時返回以下內容:數組現在包含正確的內容,但看起來與我需要的不同,這可能是為什么在我的JS中使用它不起作用。
當前數組如下(縮短):
Array ( [0] => Array ( [text] => item 1 [weight] => 20 ) [1] => Array ( [text] => item 2 [weight] => 19 ) [2] => Array ( [text] => item 3 [weight] => 18 ) [3] => Array ( [text] => item 4 [weight] => 17 ) [4] => Array ( [text] => item 5 [weight] => 16 ) )
有沒有辦法可以將其轉換為JavaScript數組,看起來像下面這是我需要的函數呢?
var word_array = [
{text: "item 1", weight: 20},
{text: "item 2", weight: 19},
{text: "item 3", weight: 18},
{text: "item 4", weight: 17},
{text: "item 5", weight: 16},
];
不幸的是,我不能在這里提供更多,因為我不知道如何做到這一點。 我嘗試簡單地將它回顯到JS變量中,但這不起作用,因為格式不是函數所期望的。
蒂姆,非常感謝任何提示。
為此你必須編寫自己的函數。 這個應該工作,但不必:
$json = "[ \n";
foreach($array as $element) {
$obj = array();
foreach($element as $key => $val) {
if(is_numeric($val)) {
$obj[] = $key.": ".$val;
} else {
$obj[] = $key.": \"".$val."\"";
}
}
$json .= "{".implode(", ", $obj)."},\n";
}
$json .= "\n ];";
$.getJSON('/phpscript.php', function(data){
var word_array = data;
})
你永遠不應該直接回復PHP代碼到js,通過ajax獲取它。 了解web2.0的概念,這樣你就可以在php開發中領先一步,而你的同行仍在使用過時的MVC和其他策略。
服務器端你應該使用它來返回你的數組:
die(json_encode($array));
一旦你將陣列重新放入js,你將需要學會使用它。 首先,使用控制台日志記錄它
console.log(word_array);
您應該在瀏覽器的控制台選項卡中看到一個帶有鍵名/值的對象。
現在你需要使用它。
for(var i = 0; i < word_array.length; i++){
$('#example').append('<p>'+word_array[i].keyname+'</p>');
}
其中keyname
是您要訪問的數組的鍵。
簡單地使用此代碼
PHP
$arr_ouput = array();
foreach($clould as $arr)
{
$arr_temp = array();
foreach($arr as $key=>$val)
{
$str2 = $key.':"'.$val.'"';
$arr_temp[] = $str2;
}
$str_temp = '{'.implode(",", $arr_temp).'}';
$arr_ouput[] = $str_temp;
}
$str = '['.implode(",", $arr_ouput).']';
JS
<script>
var word_array = <?php echo $str;?>;
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.