Remove index based json object name in php [duplicate] - php

This question already has answers here:
PHP Array to JSON Array using json_encode(); [duplicate]
(4 answers)
Closed 5 years ago.
I tried real hard for my title to make sense haha. I have this JSON:
[{
"0": {
"id": 130427,
"created_at": 1512521776301,
"updated_at": 1512549188911,
"category": 0,
"platform": 6,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 76663
},
"2": {
"id": 131795,
"created_at": 1514172411633,
"updated_at": 1514190849639,
"category": 0,
"platform": 39,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 78658
}
}]
As you can see the position of the JSON object in the global json serves as the name of the object and I don't want this. This is what I want:
[{
"id": 130427,
"created_at": 1512521776301,
"updated_at": 1512549188911,
"category": 0,
"platform": 6,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 76663
},
{
"id": 131795,
"created_at": 1514172411633,
"updated_at": 1514190849639,
"category": 0,
"platform": 39,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 78658
}
]
I want the objects without a name. This is the code I'm using:
$json = file_get_contents('./releases.json');
$data = json_decode($json, TRUE);
$region = isset($_GET['region']) ? $_GET['region'] : null;
# if region is not null: ?region=8
if ($region) {
$region_filter = function($v) use ($region) {
// 8 == Worldwide
if ($v['region'] == $region || $v['region'] == 8) {
return true;
} else {
return false;
}
};
$data = array_filter($data['data'], $region_filter);
}
header('Content-Type: application/json');
echo json_encode(array($data)); // good
Thank you

You need to use array_values() to reindex the array.
PHP's json_encode() function will only produce an array if all array keys are numeric and don't have any gaps, e.g. 0, 1, 2, 3 etc. The problem is that array_filter() can remove certain keys and leave gaps, which causes json_encode() to include the keys as you show in your example. You can fix this by using array_values() to re-index the array before calling json_encode().
Here is an example:
<?php
// numeric array keys with no gaps
$a = ['a', 'b', 'c'];
echo json_encode($a);
// ["a","b","c"]
// filter out the 'b' element to introduce a gap in the keys
$a = array_filter($a, function ($v) {
return $v !== 'b';
});
echo json_encode($a);
// {"0":"a","2":"c"}
// re-index the array to remove gaps
$a = array_values($a);
echo json_encode($a);
// ["a","c"]

Related

PHP - Remove empty menus

Good afternoon guys, I'm having a hard time finding the solution to this simple problem, I hope someone can help me.
I have a recursive array automatically generated by the source code, I use this array as the system's menu tree, however, it goes through a permission system, and some submenus are excluded, leaving certain menus empty, follow the example in JSON:
{
"1": {
"id": 1,
"idFather": null,
"nome": "test 1",
"sub": {
"4": {
"id": 4,
"idFather": 1,
"nome": "test 1.1",
"sub": {}
},
"5": {
"id": 5,
"idFather": 1,
"nome": "test 1.2",
"sub": {
"7": {
"id": 7,
"idFather": 5,
"nome": "test 1.3.1",
"sub": {}
},
"8": {
"id": 8,
"idFather": 5,
"nome": "test 1.3.2",
"sub": {}
}
}
},
"6": {
"id": 6,
"idFather": 1,
"nome": "test 1.3"
}
}
},
"2": {
"id": 2,
"idFather": null,
"nome": "test 2"
},
"3": {
"id": 3,
"idFather": null,
"nome": "test 3",
"sub": {
"10": {
"id": 10,
"idFather": 3,
"nome": "test 3.2"
}
}
}
}
Within key 1 I have key 4 with no other items, and I have key 5 with two keys (7 and 8), however, these 2 keys also do not contain items, so I need to remove keys 4, 7, 8 and consequently, key 5 too, as it will be empty at the end of the removals!
Note that key 6 inside key 1, key 10 inside key 3 and key 2 do not contain the "sub" element, so it must not be removed!
I am Brazilian, so my English may be a little rusty.
A simple recursive function will handle this.
Check each entry at the current level.
If it has a sub menu, call the function on the sub menu. If not, move on.
If the sub menu is now empty, remove it
The implementation looks like this:
$jsonString = "{...}"; // Your data listed above, omitted here for clarity
$menus = json_decode($jsonString);
// Pass a menu into the function.
// PHP passes objects by reference, so we're operating directly
// on the original object, hence no need for a return value.
function clearMenu(object $menu):void {
foreach($menu as $id=>$entry) {
if (isset($entry->sub)) { // If we have a submenu, handle it
clearMenu($entry->sub);
if (empty((array)$entry->sub)) { // Cast object to array to test for emptiness
unset($menu->$id); // Unset the item in the menu using the key. Unsetting the item directly doesn't work
}
}
}
}
clearMenu($menus);
$newMenus = json_encode($menus, JSON_PRETTY_PRINT);
echo "<pre>$newMenus</pre>";
Output:
{
"1": {
"id": 1,
"idFather": null,
"nome": "test 1",
"sub": {
"6": {
"id": 6,
"idFather": 1,
"nome": "test 1.3"
}
}
},
"2": {
"id": 2,
"idFather": null,
"nome": "test 2"
},
"3": {
"id": 3,
"idFather": null,
"nome": "test 3",
"sub": {
"10": {
"id": 10,
"idFather": 3,
"nome": "test 3.2"
}
}
}
}

PHP Regex to Find and replace all occurrences of a string that that starts and ends with certain characters

I am a newbie when it comes to regex. I have a json string that includes timestamp, I would like to remove all the occurrences of the date field in the string.
the beautified json string looks like this:
{
"abc": 157,
"efg": 1,
"hij": "1",
"klm": "0.00",
"created_at": {
"date": "2020-04-08 12:53:34.682759",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2020-04-08 12:53:34.682759",
"timezone_type": 3,
"timezone": "UTC"
}
}
I want to remove the all the occurrences of the string that starts with "date": " and ends with ",
so the output would look like the following:
{
"abc": 157,
"efg": 1,
"hij": "1",
"klm": "0.00",
"created_at": {
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"timezone_type": 3,
"timezone": "UTC"
}
}
I know preg_match_all can actually help find all matching occurrences, however, i found difficulties in building the pattern especially that my pattern includes commas and double quotes.
Regex (or any other string function) are not the way to edit a JSON string! You have to decode it to an array, then edit it, to finally reencode it to JSON.
$json = <<<'JSON'
{
"abc": 157,
"efg": 1,
"hij": "1",
"klm": "0.00",
"created_at": {
"date": "2020-04-08 12:53:34.682759",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2020-04-08 12:53:34.682759",
"timezone_type": 3,
"timezone": "UTC"
}
}
JSON;
$arr = json_decode($json, true);
function delete_key(&$arr, $key) {
foreach($arr as $k => &$v) {
if ( $k === $key ) {
unset($arr[$k]);
continue;
}
if ( is_array($v) ) {
delete_key($v, $key);
}
}
}
delete_key($arr, 'date');
print_r(json_encode($arr, JSON_PRETTY_PRINT));
demo

PHP Array Conversion with removing Array Name

Hello i want to remove "news_list" from php json array.
{
"news_list": [
{
"id": 2,
"group_id": 1,
"news_title": "fbb",
"news_description": "gfhgfh",
"status": "Y",
"created_at": "2017-05-11 16:04:26",
"updated_at": "2017-05-11 16:04:26"
},
{
"id": 3,
"group_id": 1,
"news_title": "ewrdf",
"news_description": "dsfsdfdsfsdffffffffffffff",
"status": "Y",
"created_at": "2017-05-12 10:59:01",
"updated_at": "2017-05-12 10:59:01"
}
]
}
Desired Output :
[
{
"id": 2,
"group_id": 1,
"news_title": "fbb",
"news_description": "gfhgfh",
"status": "Y",
"created_at": "2017-05-11 16:04:26",
"updated_at": "2017-05-11 16:04:26"
},
{
"id": 3,
"group_id": 1,
"news_title": "ewrdf",
"news_description": "dsfsdfdsfsdffffffffffffff",
"status": "Y",
"created_at": "2017-05-12 10:59:01",
"updated_at": "2017-05-12 10:59:01"
}
]
is there ant in-built PHP function for same ?.if there i s any in built function then please convey me.
There is nothing like direct function to fetch any key data of json. You need to convert your json to array or object using json_decode and then can perform or fetch what you looking for.
$res = json_decode($data); // return object
print_r($res->news_list);
Or
$res = json_decode($data, true); // return array
print_r($res['news_list']);
Try this...
$oldDataArray = json_decode('{"news_list":[{"id":2,"group_id":1,"news_title":"fbb","news_description":"gfhgfh","status":"Y","created_at":"2017-05-11 16:04:26","updated_at":"2017-05-11 16:04:26"},{"id":3,"group_id":1,"news_title":"ewrdf","news_description":"dsfsdfdsfsdffffffffffffff","status":"Y","created_at":"2017-05-12 10:59:01","updated_at":"2017-05-12 10:59:01"}]}');
$newDataArray = $oldDataArray->news_list;
echo '<pre>';
print_r($newDataArray);
echo '</pre>';

php - Getting JSON values from key names

I have a JSON similar to the following:
{
"name": "Activities",
"description": "Activities",
"parent_group_id": 0,
"display": "Activities",
"group_id": 7,
"stamps": [
{
"stamp_id": 14,
"name": "Stamp 14",
"rank": 2
},
{
"stamp_id": 20,
"name": "Stamp 20",
"rank": 4
}
]
},
{
"name": "Games",
"description": "Games",
"parent_group_id": 0,
"display": "Games",
"group_id": 6,
"stamps": [
{
"stamp_id": 33,
"name": "Stamp 33",
"rank": 3
},
{
"stamp_id": 31,
"name": "Stamp 31",
"rank": 1
}
]
}
I want to get a list of each of the stamp_ids seperated by commas through PHP (eg. 14,20,33,31)
I have already tried this, with no luck:
$stampsdata = json_decode($stampsjson, true);
$numberofstamps = $stampsdata['stamps']['stamp_id']);
Can anyone help?
decode the JSON with json_decode and use array_column to get the IDs.
working solution:
// true needed to transform object to associative array
// $json contains your JSON string
$data = json_decode($json, true);
$stamps = [];
foreach ($data as $obj) {
$stamps[] = array_column($obj['stamps'], 'stamp_id');
}
// implode sub arrays and concatenate string
$str = '';
foreach ($stamps as $stamp) {
$sub = implode(',', $stamp);
$str .= $sub . ',';
}
// remove trailing comma
$stampIds = rtrim($str, ',');
print ($stampIds);

Looping through an array in PHP not working as expected

I am retrieving the following array, which is the options list for a product, using the bigCommerece API. Using echo $curlProductOptions I see the following echoed to the screen:
[
{
"id": 412,
"option_id": 37,
"display_name": "testSteveMemory",
"sort_order": 0,
"is_required": true
},
{
"id": 413,
"option_id": 34,
"display_name": "Hard Drive (desktop)",
"sort_order": 1,
"is_required": true
},
{
"id": 414,
"option_id": 24,
"display_name": "Include Keyboard & Mouse",
"sort_order": 2,
"is_required": true
},
{
"id": 415,
"option_id": 33,
"display_name": "Memory",
"sort_order": 3,
"is_required": true
}
]
So I am presuming I have an array within $curlProductOptions containing the above data.
I now need to loop through each element and echo each 'option_id'.
I have tried :
foreach($curlProductOptions['option_id'] as $value)
{echo $value;}
and:
for ($i = 0; $i < count($curlProductOptions); ++$i)
{echo 'optionID ='.$curlProductOptions[$i].option_id.'<br>';}
I also tried just to echo one of the elements.
echo $curlProductOptions['option_id'][0];
echo $curlProductOptions[0]['option_id'];
What am I not understanding here?
You have json encoded string. So you need to json_decode first .
try like this:
$curlProductOptions = json_decode($curlProductOptions,true);//create associative array
foreach($curlProductOptions['option_id'] as $value){
echo $value;
}
This works fine for me:
$curlProductOptions = json_decode($curlProductOptions, true);
foreach($curlProductOptions as $value){
echo $value['option_id'];
}

Categories