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
asked Sep 18, 2013 at 15:14
Emilio Gort
3,4553 gold badges32 silver badges44 bronze badges
-
5The first is valid JSON, second is not.Amal– Amal2013年09月18日 15:16:21 +00:00Commented Sep 18, 2013 at 15:16
-
1You can't expect json_encode() to return an invalid JSONRuben Serrate– Ruben Serrate2013年09月18日 15:16:53 +00:00Commented Sep 18, 2013 at 15:16
-
1if 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?lelloman– lelloman2013年09月18日 15:19:08 +00:00Commented Sep 18, 2013 at 15:19
-
@lelloman I'm going to try..thnks for the ideaEmilio Gort– Emilio Gort2013年09月18日 15:19:46 +00:00Commented Sep 18, 2013 at 15:19
-
1yw, @RubenSerratePardo gave the answer maybe you don't need to write it ;)lelloman– lelloman2013年09月18日 15:21:10 +00:00Commented Sep 18, 2013 at 15:21
2 Answers 2
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.
answered Sep 18, 2013 at 15:19
Ruben Serrate
2,8031 gold badge21 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
lang-php