Problem with Json_encode

0

I have the following code?

if($result = $mysqli->query($query)){
    while($row = $result->fetch_array(MYSQLI_ASSOC))
    {
        $temp[] = $row;
    }
}
$result->close();



foreach ($temp as $x) {
    $x['seat_number'];       //OUTPUT: 4-12-7
    $x['payment_status'];    //OUTPUT: 2-1-2
}

How to make the $ temp array get sorted this way: [4 = > 2, 12 = > 1, 7 = > 2]

//Funciona
//echo json_encode([4 => 2, 12 => 1, 7 => 2]);

Because this 2 json_encode codes return different values:

1st

$teste = '[4 => 2, 12 => 1, 7 => 2]';
echo json_encode(utf8_encode($teste));

2nd

echo json_encode([4 => 2, 12 => 1, 7 => 2]);
    
asked by anonymous 23.01.2017 / 03:53

2 answers

1

Why in the first case you are supplying a string as a parameter. And then PHP understands that you want to encode a simple string in JSON format. And this is what is displayed. The content of the string is indifferent. It will always be a string to convert to JSON format.

The second case is an array. And PHP converts the supplied array into an array in JSON format.

For more information: link

    
23.01.2017 / 04:14
0

Because one is only a string while the other is an array.

When you do this:

echo json_encode([4 => 2, 12 => 1, 7 => 2]);

It's the same as doing this:

$array = array(4 => 2, 12 => 1, 7 => 2);
echo json_encode($array);

The [] from PHP 5.4 indicates 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 this:

$teste = '[4 => 2, 12 => 1, 7 => 2]';
echo json_encode(utf8_encode($teste));

You have a normal string, a , it's the same to do this:

echo json_encode('[4 => 2, 12 => 1, 7 => 2]');

Since the information is between ' (or " ) it is treated as a simple string and not an array anymore.

Just to complement, if your interest is to "preserve the string", you can add JSON_UNESCAPED_UNICODE to json_encode , eg:

$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);

Try this here.

In this way the $json will be a correct array and will correctly enter json_encode as an array and not a string.

    
23.01.2017 / 04:23