Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exclude some values in json_encode() with JSON_NUMERIC_CHECK

Tags:

json

php

I use CakePHP framework. I have an array which corresponds a model's records. I have to handle it in the way, that all the integers and floats are output as integers and floats just like in java without quotes(111 or 11.1 instead of this '111.1' or '11.1'). I found the way to return all the values in this way: return json_encode($data, JSON_NUMERIC_CHECK);. The question is: is there any way to exclude some numeric fields to be outpt in this way? In other words: I have two numeric fields: field1 and field2, and they have to be with quotes. Meantime all other numeric fields must be without quotes. How could I implement this ? My array looks so:

array(
    (int) 0 => array(
        'password' => '*****',
        'id' => '2',
        'number' => '2',
        'debtor_number' => null,
        'name' => 'Ziegler',
        'firstname' => 'Lisa',
        'address' => 'Frau',
        'title' => '',
        'name_extension' => '',
        'company' => '',
        'company_function' => '',
        'street' => 'Feldbergstr. 13-15',
        'street2' => null,
        'postbox' => '',
        'street_or_postbox' => '1',
        'zip' => '60318',
        'city' => 'Frankfurt am Main',
),
    (int) 1 => array(
        'password' => '*****',
        'id' => '3',
        'number' => '3',
        'debtor_number' => null,
        'name' => 'Trappatoni',
        'firstname' => 'Günther',
        'address' => 'Herr',
        'title' => '',
        'name_extension' => '',
        'company' => '',
        'company_function' => '',
        'street' => 'Trilluper Weg 17',
        'street2' => null,
        'postbox' => '',
        'street_or_postbox' => '1',
        'zip' => '60594',
        'city' => 'Frankfurt am Main',
like image 725
handkock Avatar asked May 22 '26 04:05

handkock


1 Answers

First of all, a little example of how JSON_NUMERIC_CHECK works:

$data = [112, '34', 5.6, '7.8'];
echo json_encode($data) . PHP_EOL;
echo json_encode($data, JSON_NUMERIC_CHECK) . PHP_EOL;

... prints:

[112,"34",5.6,"7.8"]
[112,34,5.6,7.8]

There isn't any feature to determine which values should be parsed (and if they wanted to add it, what would its syntax be?). The only way to get the results you want is to ensure that source data is already using the appropriate PHP data types. And that's something you can certainly do (though the exact details depend on your specs):

$person = [
   'age' => 33,
   'zip_code' => '09007',
];
$person['age'] = is_null($person['age']) ? null : (int)$person['age'];
echo json_encode($person);

... prints:

{"age":33,"zip_code":"09007"}
like image 75
Álvaro González Avatar answered May 24 '26 18:05

Álvaro González