Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert php associative array into javascript object

I'm trying to load Chinese words as keys, and their English translations as values from a database into a php array so then I can use them on the client side in JavaScript. So I load the PHP key:value pairs into the JavaScript array and try to output the results as key value pair as such:

stuff : Ni, You 
stuff : Ta, Him or Her
stuff : Wo, I

Chinese and English words are loaded in a relational database.

PHP:

$wordsArray = array();               
while ($row = $sql->fetch_assoc()) {
    $wordsArray[$row['chinese']] = $row['english'];
}

Javascript: Here I want the $.each to output the key as a string, and not a number index. So when I tried var words = [<?php echo '"'.implode('","', $wordsArray).'"' ?>]; as an array, I got:

stuff : 0, You 
stuff : 1, Him or Her
stuff : 2, I

When I'm really looking for:

stuff : Ni, You 
stuff : Ta, Him or Her
stuff : Wo, I

So I changed words to be an object so that $.each could output key as string:

var words = {<?php echo '"'.implode('","', $wordsArray).'"' ?>};
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});

Which throws error: SyntaxError: Unexpected token ,

like image 601
user3871 Avatar asked Jan 16 '14 05:01

user3871


4 Answers

You can use json_encode() to make array as an json object like,

var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});
like image 168
Rohan Kumar Avatar answered Oct 16 '22 16:10

Rohan Kumar


I looked a lot for an elegant solution to fix this issue without doing changing things over javascript or just replace quotes via preg_replace (for the case that the values would contain quotes) and end up doing it by myself. even if it's too late, I hope it would help those who are looking for the same solution.

function json_encode_advanced(array $arr, $sequential_keys = false, $quotes = false, $beautiful_json = false) {

    $output = "{";
    $count = 0;
    foreach ($arr as $key => $value) {

        if ( isAssoc($arr) || (!isAssoc($arr) && $sequential_keys == true ) ) {
            $output .= ($quotes ? '"' : '') . $key . ($quotes ? '"' : '') . ' : ';
        }

        if (is_array($value)) {
            $output .= json_encode_advanced($value, $sequential_keys, $quotes, $beautiful_json);
        } else if (is_bool($value)) {
            $output .= ($value ? 'true' : 'false');
        } else if (is_numeric($value)) {
            $output .= $value;
        } else {
            $output .= ($quotes || $beautiful_json ? '"' : '') . $value . ($quotes || $beautiful_json ? '"' : '');
        }

        if (++$count < count($arr)) {
            $output .= ', ';
        }
    }

    $output .= "}";

    return $output;
}

function isAssoc(array $arr) {
    if (array() === $arr) return false;
    return array_keys($arr) !== range(0, count($arr) - 1);
}

usage:

$array = [
    'someField' => '"value"', // double quotes for string if needed
    'labelField' => '"label"', // double quotes for string if needed
    'boolean' => false,
    'numeric' => 5,
    'render' => [
        'option' => 'function() {
            console.log("Hello World!");
            console.log(\'Hello World!\');
        }',
    ],
];
echo json_encode_advanced($array);

result:

{
    someField : "value",
    labelField : "label",
    boolean : false,
    numeric : 5,
    render : {
        option : function() {
            console.log("Hello World!");
            console.log('Hello World!');
        }
    }
}
like image 24
pixxet Avatar answered Oct 16 '22 14:10

pixxet


The answer of Rohan Kumar is excellent except it uses jQuery to show the results.

This can be quicker and easier:

var words = <?php echo json_encode( $wordsArray ) ?>;
console.dir(words);

This gives you a one line result like Object ▶. Clicking on the will open the object and shows its contents.

like image 3
Harm Avatar answered Oct 16 '22 16:10

Harm


For me the simplest way to convert php array to javascript object is to json_encode the php array then JSON.parse it from javascript like this:

<?php 
    $array = [1 => "one", 2 => "two", 3 => "three"];
?>

<script>
    const jsObject = JSON.parse(`<?= json_encode($array) ?>`)
    console.log(jsObject) // Object { 1: "one", 2: "two", 3: "three" }
</script>
like image 3
Djamel KHIREDDINE Avatar answered Oct 16 '22 15:10

Djamel KHIREDDINE