2

I have this simple json object:

$colours = '{"num":20,"status":"ok","colour0":"red","colour1":"green","colour2":"blue"}';

How can I turn into this with PHP:

$colours = '[{"colour":"red"},{"colour":"green"},{"colour":"blue"}]';

Do I need to json_decode() it first ?

I tried this with no luck:

$jsonArr = json_decode($similarsites, true);
$c1 = parse_url($jsonArr['c1']);

$ii = 0;
$resulti = array('color' => array());

while (isset($jsonArr['c' . $ii])) {
        $c = $jsonArr['c' . $ii];

        $resulti['color'][$ii] = $c;
        $ii++ ;
    }

print json_encode($resulti['color']);

But this gives me the list of all colours not as key/value

11
  • 1
    You can't have the same key multiple times in an object. Commented Jan 15, 2014 at 8:58
  • @Barmar Sorry please check my edit Commented Jan 15, 2014 at 8:59
  • You would be better off just returning an array of colours, e.g. {"red","green","blue"} Commented Jan 15, 2014 at 8:59
  • 1
    @Ryan No, his edit solves the problem. Now he has an array of objects, not a single object. Commented Jan 15, 2014 at 9:00
  • 1
    @Barmar I see now, it updated then reverted for me so I saw his original post. It's now showing correctly. Commented Jan 15, 2014 at 9:01

1 Answer 1

1
$ii = 0;
$resultArr = array();
while (isset($jsonArr['colour' . $ii])) {
    $resultArr[] = array('colour' => $jsonArr['colour' . $ii]);
    $ii++;
}

DEMO

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

9 Comments

sir this line gives me an error: $resultArr[] = array('colour' => $jsonArr['colour' + $ii]));
Sorry, I had an extra parenthesis
Thank you. After if I use: print json_encode($resultArr); Ι just get two brackets: [] - or an empty json object
It seems that isset($jsonArr['colour' + $ii]) is false because right after that I am echo "empty"; with no result
Fixed it. + should be . (too much switching between PHP and JS). And i++ should be $ii++.
|

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.