0

So I have this string:

[{values: {"US" : "rgba(29, 79, 207, 1)"}},{values: {"NL" : "rgba(29, 79, 207, 1)"}}] This string sets colours for jvectormap. the entire reason for this function, I will only show countries that visited.

It's from Javascript, and I need to use this same format but in PHP and I think it has something to do with json encode but I can't get it to work.. So what I want to do is make an array into this string.. How would I do that?

When I make an array in PHP and encode it to json, this comes out: [["NL","black"],["US","blue"]] and this format wont work of course.

1
  • 1
    json_decode($string); Commented Sep 28, 2014 at 18:14

1 Answer 1

1

You've supplied invalid JSON. values needs to be quoted to become "values", for PHP to decode it.

<?php

$string = <<<JSON
[{"values": {"US" : "rgba(29, 79, 207, 1)"}},{"values": {"NL" : "rgba(29, 79, 207, 1)"}}]
JSON;

echo print_r( json_decode($string, true), true);

https://eval.in/199639

An excellent JSON checker is http://json.parser.online.fr

You'd then create your array like;

$array = array (
  0 => 
  array (
    'values' => 
    array (
      'US' => 'rgba(29, 79, 207, 1)',
    ),
  ),
  1 => 
  array (
    'values' => 
    array (
      'NL' => 'rgba(29, 79, 207, 1)',
    ),
  ),
);
echo json_encode($array);

https://eval.in/199684

Sign up to request clarification or add additional context in comments.

5 Comments

I don't want PHP to decode it, I want to generate javascript code in the format that I posted by using an array (php).
Yes and that's exactly what my question is.
If I need to generate it like that I'd be better off making a pattern for the string. There must be an easier way so it can be done within a loop..
Sorry, now I'm confused. You want the array structure, but create it within a loop?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.