convert php associative array into javascript object

后端 未结 5 972
花落未央
花落未央 2020-12-28 15:52

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.

相关标签:
5条回答
  • 2020-12-28 16:03

    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>
    
    0 讨论(0)
  • 2020-12-28 16:06

    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.

    0 讨论(0)
  • 2020-12-28 16:10

    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 讨论(0)
  • 2020-12-28 16:18

    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);
    });
    
    0 讨论(0)
  • 2020-12-28 16:18

    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!');
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题