1

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 i.e.,

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

4
  • 1
    Can you show the php array. Commented Dec 5, 2017 at 17:36
  • Question UPdated please see Commented Dec 5, 2017 at 17:49
  • Well that isn't a zero indexed array, it's an associative array. So I'm guessing what you actually have is a multidimensional zero indexed array which is filled with associative arrays, and you are outputting the whole thing. Commented Dec 5, 2017 at 17:55
  • Without some sort of transformation of the array on the backend, you'll never get what you are expecting. The code that creates the PHP array must be modified. Commented Dec 5, 2017 at 18:12

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Thats showing Uncaught SyntaxError: Unexpected token , in JSON at position 0 at JSON.parse (<anonymous>) at HTMLDocument.<anonymous> (question:533) at j (jquery.min.js:2) at k (jquery.min.js:2)
My mistake @pokemon, I misstyped based on reading your post. try my edit. You do not need "array_keys" - using my exact code, I was able to get what you are looking for.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.