简体   繁体   中英

Converting PHP array to a single JSON object using js

I have a php array(zero indexed) which I am sending to front end directly by echoing its json_encode format.

I want the JSON object to look like

{
    'A': null,
    'B': null,
    'C': null
}

But when I tried console.log ie,

console.log(<?php echo json_encode($array); ?>)

its printing js array

Also when I try print_r($array) in backend it prints

[array] => Array
    (
        [0] => A
        [1] => B
        [2] => C

    )

Thanks in advance

This code gives you the desired out put

$array = array
    (
        '0' => 'A',
        '1' => 'B',
        '2' => 'C'

    );
    $array = array_fill_keys($array, NULL);

echo json_encode($array);

Out Put:

{"A":null,"B":null,"C":null}

Javascript:

<script type="text/javascript">
<!--
var data =<?php echo json_encode($array); ?>;

console.log(data);
//-->
</script>

Out Put:

 Object {A: null, B: null, C: null}
    A:null
    B:null
    C:null

Why not just make your PHP array an array of ['A' => null, 'B' => null...]

Otherwise, your other option would be:

   $newArray = array_fill_keys($tags, null);
   json_encode($newArray);

This would take each array element in $tags, and set it as your index in newArray with a value of null.

Based on your code, you would have:

<?php $newArray = array_fill_keys($tags, null);
$json = json_encode($newArray); ?>
console.log(JSON.parse(<?= $json; ?>));

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