Because one is only a string while the other is an array.
When you do that:
echo json_encode([4 => 2, 12 => 1, 7 => 2]);
It’s the same as doing it:
$array = array(4 => 2, 12 => 1, 7 => 2);
echo json_encode($array);
The []
from PHP 5.4 indicate an array, so this array(4 => 2, 12 => 1, 7 => 2)
and this [4 => 2, 12 => 1, 7 => 2]
are also recognized as an array.
When you do that:
$teste = '[4 => 2, 12 => 1, 7 => 2]';
echo json_encode(utf8_encode($teste));
You have a normal string, a text, is the even to do this:
echo json_encode('[4 => 2, 12 => 1, 7 => 2]');
Once the information is between '
(or "
) is treated as a simple string and no longer an array.
Just to complement, if your interest is "preserving the string", you can add the JSON_UNESCAPED_UNICODE
at the json_encode
, example:
$teste = [4 => 'ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ.', 12 => '側経意責家方家閉討店暖育田庁載社転線宇'];
echo json_encode($teste, JSON_UNESCAPED_UNICODE);
// Resultado:
// {"4":"ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ.","12":"側経意責家方家閉討店暖育田庁載社転線宇"}
echo json_encode($teste);
// Resultado sem o `JSON_UNESCAPED_UNICODE`:
// {"4":"\u16a0\u16c7\u16bb\u16eb\u16d2\u16e6\u16a6\u16eb\u16a0\u16b1\u16a9\u16a0\u16a2\u16b1\u16eb\u16a0\u16c1\u16b1\u16aa\u16eb\u16b7\u16d6\u16bb\u16b9\u16e6\u16da\u16b3\u16a2\u16d7.","12":"\u5074\u7d4c\u610f\u8cac\u5bb6\u65b9\u5bb6\u9589\u8a0e\u5e97\u6696\u80b2\u7530\u5e81\u8f09\u793e\u8ee2\u7dda\u5b87"}
EDIT:
Use only this:
// Acima disto sem alteração!
$result->close();
foreach($temp as $x){
$json[ $x['seat_number'] ] = $x['payment_status'];
}
echo json_encode($json);
Test it out here.
Thus the $json
will be a correct array and will enter correctly into json_encode
as an array and not a string.
related: http://answall.com/q/141036/4793
– Daniel Omine