0

I'm trying to create a PHP script to generate JSON data for a jqplot bubble chart. The jqplot sample code requires data in the format

var arr = [ 
  [45, 92, 1067, {label:"Alfa Romeo", color:'skyblue'}], 
  etc.
];

My script is along the lines of

while ...
  array_push(
    $arrBubble, 
    array(
      11, 
      123, 
      1236,
      json_encode(
        array('label' => $car, 'color' => 'skyblue')
      )
  );
} 
echo json_encode($arrBubble);

The problem is that the result is

[ [11, 123, 1236, "{\"label\":"VW", \"color\":\"skyblue\"}"] ]

The double json_encode has encoded the object(?) as a literal string.

What's the best way to work around this?

2
  • 1
    Why do you keep the json_encode in the loop then? Commented Jul 22, 2018 at 18:53
  • How else can I add the {label:"Alfa Romeo", color:'skyblue'} into the array for subsequent inclusion in the required JSON (but without encoding as a string)? Commented Jul 22, 2018 at 18:57

1 Answer 1

1

There is no reason to explicitly have a json_encode for one of the values inside the array. When you're using json_encode, it'll convert each level of the array as you expect.

var_dump(json_encode([
  11, 
  123, 
  1236,
  ['label' => $car, 'color' => 'skyblue']
]));

Outputs the structure you want:

string(48) "[11,123,1236,{"label":"VW","color":"skyblue"}]"
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastically simple, thank you. I knew I was missing something straight-forward. Tested and working.

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.