Simplifying my JSON to build a array. - php

I am trying to take my JSON input and generate a easy array to search in, but it is as far as I can tell giving me some trouble.
First of, this is my JSON as is, loaded from a file:
{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}
Is there a way to simplify this or minimise the number of arrays?
I have been using the following code to preview my array, but I am trying to get it to search for id and then print the values for id, boat and name.
$json_url = "teams.json";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo '<pre>';
print_r($data);
echo '</pre>';

This is really quite simple. There is no need to convert a perfectly good object into an array, it only makes life more complex.
The only array you have in your data structure is the teams array and that is easily processed like this
$json = '{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}';
$data = json_decode($json);
//print_r($data);
foreach ($data->teams as $object) {
if ( $object->id == 2) {
echo 'boat is ' . $object->boat . ' and name is ' . $object->name . PHP_EOL;
}
}
And the result of the above example would be
boat is Test 2 and name is Name Test 2

Related

Rewrite json in loop

I have an array, which i wrote like a table for more reability.
[{
"id": "1",
"title": "boune",
"value": "3"
}, {
"id": "2",
"title": "check",
"value": "4"
}, {
"id": "3",
"title": "boune",
"value": "5"
}]
As the result of what i want to see is this json, where 'value' of identical 'titles' united inside [] brackets. I am very newbie in php. I undestand that i need for loop to sort query result, but can`t heck...Cant even put my mind to it...
[{
"id":"1",
"title": "boune",
"value": [3, 5]
}]
<?php
$json = '[{"id":"1","title":"boune","value":"3"},{"id":"2","title":"check","value":"4"},{"id":"3","title":"boune","value":"5"}]';
$json_data = json_decode($json,true);
function accumulateValuesByTitle($json_data){
$hash = [];
foreach($json_data as $each_record){
if(isset($hash[$each_record['title']])){
$hash[$each_record['title']]['value'][] = $each_record['value'];
if($hash[$each_record['title']]['id'] > $each_record['id']){
$hash[$each_record['title']]['id'] = $each_record['id'];
}
}else{
$hash[$each_record['title']] = $each_record;
$hash[$each_record['title']]['value'] = [$hash[$each_record['title']]['value']];
}
}
return array_values($hash);
}
$modified_data = accumulateValuesByTitle($json_data);
echo json_encode($modified_data);

Filter array elements based on value of a key element for Given IDs

I have a JSON object in PHP Like
$my_json = '[{
"No": "1",
"Id": "10",
"msg": "Value is 10"
},
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
}, {
"No": "4",
"Id": "95",
"msg": "value is 95 "
} ]';
I have converted it to PHP object array using $obj_arr= json_decode($my_json);
Now, based on user selection I want to filter array element
Eg. if the user selects "ID" as 38 and 55 then new array should note have ID 10 and 95 IN it and must contain all other data related to those ID just like an original one
EG
$final_json = '[
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
} ]';
Try this:
<?php
$my_json = '[{
"No": "1",
"Id": "10",
"msg": "Value is 10"
},
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
}, {
"No": "4",
"Id": "95",
"msg": "value is 95 "
} ]';
$selected = [38, 55];
$obj = json_decode($my_json);
$result = array_filter($obj, function($row) use ($selected) {
return in_array($row->Id, $selected);
});
echo json_encode(array_values($result), JSON_PRETTY_PRINT);
Output:
[
{
"No": "2",
"Id": "55",
"msg": "value is 55"
},
{
"No": "3",
"Id": "38",
"msg": "value is 38 "
}
]
If you want to filter out the selected values above instead of keep them, return the negation of in_array.

Displaying key/value in PHP object

In PHP, how can I make this data:
{
"items": {
"item": [{
"id": "59",
"type": "Domain",
"relid": "27",
"description": "Sample Monthly Product(01\ / 01\ / 2016 - 31\ / 01\ / 2016)",
"amount": "180.00",
"taxed": "0"
}]
}
}
Have this format:
{
"items[item][0][id]": "59",
"items[item][0][type]": "Domain",
"items[item][0][relid]": "27",
"items[item][0][description]": "Sample Monthly Product (01\/01\/2016 - 31\/01\/2016)",
"items[item][0][amount]": "180.00",
"items[item][0][taxed]": "0"
}
Reason: Setting up a Zap (via Zapier) using email parser to import invoices from WHMCS, and it seems to work with parsing data when 2nd format (items[item][0][id]) to read the line descriptions but not when using the 1st. In the WHMCS API ref it shows it outputting as the 2nd format but can't see why mine looks like 1st (developers.whmcs.com/api-reference/getinvoice)
I think this might work with your current setup:
<?php
//assuming your current dataset isn't in JSON, you can ignore this part
$json = '{
"items": {
"item": [{
"id": "59",
"type": "Domain",
"relid": "27",
"description": "Sample Monthly Product",
"amount": "180.00",
"taxed": "0"
},
{
"id": "203",
"type": "Server",
"relid": "86",
"description": "Sample Yearly Product",
"amount": "290.00",
"taxed": "1"
}]
}
}';
$json = json_decode($json, true);
$parsed = array();
foreach ($json['items']['item'] as $index => $item)
foreach ($item as $attr => $val)
$parsed['items[item][' . $index . '][' . $attr . ']'] = $val;
echo json_encode($parsed);
Output:
{
"items[item][0][id]": "59",
"items[item][0][type]": "Domain",
"items[item][0][relid]": "27",
"items[item][0][description]": "Sample Monthly Product",
"items[item][0][amount]": "180.00",
"items[item][0][taxed]": "0",
"items[item][1][id]": "203",
"items[item][1][type]": "Server",
"items[item][1][relid]": "86",
"items[item][1][description]": "Sample Yearly Product",
"items[item][1][amount]": "290.00",
"items[item][1][taxed]": "1"
}

Add field to a JSON file

I have a very simple JSON file "json.txt" :
{
"status": true,
"data":
{
"clics":
[
{
"id": "1",
"title": "Title 1",
"comment": "Blablabla 1",
"url": "http://photostodisplay/1.jpg"
},
{
"id": "2",
"Title": "Title 2",
"comment": "Blablabla 2",
"url": "http://photostodisplay/2.jpg"
}
]
}
}
and I would like to add data and get the following result :
{
"status": true,
"data":
{
"clics":
[
{
"id": "1",
"title": "Title 1",
"comment": "Blablabla 1",
"url": "http://photostodisplay/1.jpg"
},
{
"id": "2",
"Title": "Title 2",
"comment": "Blablabla 2",
"url": "http://photostodisplay/2.jpg"
},
{
"id": "3",
"Title": "Title 3",
"comment": "Blablabla 3",
"url": "http://photostodisplay/3.jpg"
}
]
}
}
The php code I use return the following error :
Fatal error: Cannot use object of type stdClass as array in /home/XXXX/www/clic/test.php on line 10
Here is the php code
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$newdata = array('id'=>'11', 'title' => 'sfdfsdfqf', 'comment' => 'sfdfwwfwdsdfqf', 'url' => 'sdfqwsfsdqqfqqqsfcq');
$data[] = $newdata;
file_put_contents($file, json_encode($data));
echo OK
?>
EDIT - Cezary answer gives almost what I need but is not. Here is what I get :
{
"status": true,
"data": {
"clics": [
{
"id": "1",
"title": "Title 1",
"comment": "Blablabla 1",
"url": "http://photostodisplay/1.jpg"
},
{
"id": "2",
"Title": "Title 2",
"comment": "Blablabla 2",
"url": "http://photostodisplay/2.jpg"
}
]
},
"0": {
"id": "11",
"title": "sfdfsdfqf",
"comment": "sfdfwwfwdsdfqf",
"url": "sdfqwsfsdqqfqqqsfcq"
}
}
The issue lies with this bit of code:
$data = json_decode(file_get_contents($file));
This returns an object, not an associative array. Change that line to this:
$data = json_decode(file_get_contents($file), true);
The second argument in json_decode specifies whether you want an associative array or not, and it defaults to false.
EDIT:
You're currently adding something to the root array. To add to the clics array, you can replace $data[] = $newdata; with:
$data['data']['clics'][] = $newdata;
Shouldn't that be
$data["data"]["clics"][]=$newdata;
or
array_push($data["data"]["clics"],$newdata);

PHP's json_decode() with this JSON string

I have this JSON string:
{
"name": "test task1",
"desc": "test desc1",
"id": "1"
}{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}
But it looks like it's not correct (JSONLint tells me) so PHP's json_decode()can't decode it. There's any way to separate the two JSON arrays into two strings (or into how much string the arrays are) for making json_decode decode them?
Assuming your intention is to have an array of two elements, your JSON should look like:
[
{
"name": "test task1",
"desc": "test desc1",
"id": "1"
},{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}
]
the most straightforward
$str = ' {
"name": "test task1",
"desc": "test desc1",
"id": "1"
}{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}';
var_dump(json_decode('['.str_replace('}{','},{',$str).']'));
<?php
$str='{
"name": "test task1",
"desc": "test desc1",
"id": "1"
}{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}';
$arrays = explode("{", $str);
foreach($arrays as &$arr) $arr='{'.$arr;
//decode
foreach ($arrays as $arr) print_r(json_decode($arr,true));

Categories