简体   繁体   中英

PHP / JS: convert PHP array to JavaScript array

I have a PHP array ( $cloud ) that, after using json_encode , returns the following when I print it: The array contains the correct content now but looks different to what I need which is probably why using it in my JS doesnt work.

The current array looks as follows (shortened):

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

Is there a way I can convert this to a JavaScript array that looks like the following which is what I need for a function there ?

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},
];

Unfortunately I cannot provide more here as I don't know how this could be done. I tried simply echoing it out into the JS variable but that doesn't work as the format is not what the function expects.

Many thanks for any hints, Tim.

For that you have to write your own function. This one should work, but doesn't have to:

$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;
})

you should never echo php code into js directly, get it via ajax. learn about the concepts of web2.0 so you can be ahead of the curve in php development, while your peers are still using outdated MVC and other strategies.

server side you should use this to return your array:

die(json_encode($array));

once you get the array back into js, you will need to learn to work with it. first of all, log it with console log

console.log(word_array);

you should see an object with the key names/values in the console tab of your browser.

now you need to work with it.

for(var i = 0; i < word_array.length; i++){

   $('#example').append('<p>'+word_array[i].keyname+'</p>');

}

where keyname is the key of the array you want to access.

simple use this code

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>

WORKING DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM