32

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 ,

5 Answers 5

60

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);
});
2
  • var dp1 = <?php echo json_encode( $dataPoints1 ) ?>; console.log(dp1); still gives me Array to string conversion error can you please see my question related to it ?
    – Moeez
    Apr 18, 2020 at 0:19
  • 1
    Very important don't forget the semi-colon at the end of the php closing tag ?>;. Otherwise you will receive an error SyntaxError: unexpected token: identifier. May 7, 2020 at 15:22
7

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

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!');
        }
    }
}
3

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.

1
  • var dp1 = <?php echo json_encode( $dataPoints1 ) ?>; console.log(dp1); still gives me Array to string conversion error can you please see my question related to it ?
    – Moeez
    Apr 18, 2020 at 0:19
2

I just changed a few things to make it more compatible (line 3 and 29):

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

    $output = isAssoc($arr) ? "{" : "[";
    $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 .= isAssoc($arr) ? "}" : "]";

    return $output;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.