0

I have already read this question and doesn't answer my issue.

I have an Array like this:

Array
(
    [0] => Array
        (
            [COM] => 10659.68
        )

    [1] => Array
        (
            [MCD] => 1219.09
        )

    [2] => Array
        (
            [MCR] => 77047.65
        )

)

And when I make a json_encode() it return this;

[{"COM":10659.68},{"MCD":1219.09},{"MCR":77047.65}]

What I need is get the data in this way:

[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]

Any idea how can I achieve this

6
  • 5
    The first is valid JSON, second is not. Commented Sep 18, 2013 at 15:16
  • 1
    You can't expect json_encode() to return an invalid JSON Commented Sep 18, 2013 at 15:16
  • 1
    if you are sure about the format of the content of each string I think you could make a regex replace on the json_encode output, did you try? Commented Sep 18, 2013 at 15:19
  • @lelloman I'm going to try..thnks for the idea Commented Sep 18, 2013 at 15:19
  • 1
    yw, @RubenSerratePardo gave the answer maybe you don't need to write it ;) Commented Sep 18, 2013 at 15:21

2 Answers 2

4

Even though that's not a valid JSON, you can replace the { with [

echo str_replace(array('{','}'),array('[',']'),json_encode($your_array)); 

Depending on the content you might need a more complex replacement with regular expressions.

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

Comments

1

More complex solution:

function toJson($arr){
    $return = array();
    foreach($arr as $k => $v){
        if(is_array($v)) $return[] = toJson($v);
        else $return[] = sprintf('"%s":%s', $k, $v);
    }
    return sprintf('[%s]', implode(',', $return));
}

Test:

$input = array(
    array('COM' => '10659.68'),
    array('MCD' => '1219.09'),
    array('MCR' => '77047.65'), 
);
var_dump(toJson($input));

string(51) "[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]"

Comments

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.