Want to get the name of the collection i am accessing, - php

I am programming a adminpanel with charts etc. Now I want to access a collection but before i can do that I need to know the name of the collection. So I can use that in the method itself
this is the snippet
{
"335": [],
"338": [
{
"id": 114,
"uuid": "",
"creator": null,
"ip": "",
"version": 338,
"time": "1526806163720"
},
{
"id": 115,
"uuid": "",
"creator": null,
"ip": "",
"version": 338,
"time": "1526806269412"
}
],
"340": [],
"389": [],
"393": [],
"401": [],
"404": []
}
As you can see every collection that is in this collection has a name.
When I am using this piece of code it doesnt give me a way to get to the name to use it in the switch statement.
foreach ($toConvert as $convert) {
switch ($convert) {
Does anyone know if this can be done or is this a limitation of laravel 5.7?

Use:
foreach ($toConvert as $name => $convert) {
switch ($name) {
...
The second form will additionally assign the current element's key to the $key variable on each iteration.
You can read more here: http://php.net/manual/en/control-structures.foreach.php

Related

Printing a nested JSON Array value [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 months ago.
I've been trying to find ways to print the individual data but can't seem to figured out where I'm going wrong.
I started with this but I get no results. Before this I tried nesting loops but also got nowhere either.
$data = curl_exec($ch);
$d = json_decode($data, true);
foreach($d as $k=>$v){
echo $v['value']['displayName'];
}
Then I tried the following with only got me some of the results. I'm not sure where I'm going wrong with this.
foreach(json_decode($data,true) as $d){
foreach($d as $k=>$v){
foreach($v as $kk=>$vv){
echo $kk.$vv;
}
}
}
The JSON looks like the following:
{
"value": [
{
"id": "",
"name": "",
"etag": "",
"type": "Microsoft.SecurityInsights/alertRules",
"kind": "Scheduled",
"properties": {
"incidentConfiguration": {
"createIncident": true,
"groupingConfiguration": {
"enabled": false,
"reopenClosedIncident": false,
"lookbackDuration": "PT5M",
"matchingMethod": "AllEntities",
"groupByEntities": [],
"groupByAlertDetails": null,
"groupByCustomDetails": null
}
},
"entityMappings": [
{
"entityType": "Account",
"fieldMappings": [
{
"identifier": "FullName",
"columnName": "AccountCustomEntity"
}
]
},
{
"entityType": "IP",
"fieldMappings": [
{
"identifier": "Address",
"columnName": "IPCustomEntity"
}
]
}
],
"queryFrequency": "P1D",
"queryPeriod": "P1D",
"triggerOperator": "GreaterThan",
"triggerThreshold": 0,
"severity": "Medium",
"query": "",
"suppressionDuration": "PT1H",
"suppressionEnabled": false,
"tactics": [
"Reconnaissance",
"Discovery"
],
"displayName": "MFA disabled for a user",
"enabled": true,
"description": "Multi-Factor Authentication (MFA) helps prevent credential compromise. This alert identifies when an attempt has been made to diable MFA for a user ",
"alertRuleTemplateName": null,
"lastModifiedUtc": "2022-11-14T02:20:28.8027697Z"
}
},
...
...
...
Here is how you can get the display name without a loop. Notice that the 0 is the key value of the array since it doesn't have a name.
We start from the value, and we move one layer deeper by selecting the first array 0. Now we need to select the properties and finally, we can get the displayName from there.
$displayName = $d["value"][0]["properties"]["displayName"];
echo($displayName);
/*
Here is a quick demonstration:
value:
{
0:
{
...
properties:
{
...
displayName: [We made it!]
}
}
}
*/
And here is a very good post that explains this in more detail
How to decode multi-layers nested JSON String and display in PHP?

How to delete JSON Element in PHP?

I have a JSON object key element that i want to delete.
Lets say i want to delete the element of everything inside 'v8fe3m'
I tried using unset and delete. Nothing seems work unless my syntax is wrong.
{
"projects": {
"587ye4": {
"name": "abc",
"ip": "zz",
"loc": "azz"
},
"v8fe3m": {
"name": "japan",
"ip": "aaa",
"loc": "123",
"backups": {
"HELLO_1595524710053": {
"ts": 1595524710053,
"name": "HELLO",
"size": 770641
},
"HELLO_1595524717330": {
"ts": 1595524717330,
"name": "HELLO",
"size": 770641
},
"HELLO_1595524717558": {
"ts": 1595524717558,
"name": "HELLO",
"size": 770698
}
}
},
"x0190a": {
"name": "dubai",
"ip": "101",
"loc": "UAE"
}
}
}
$user_token = $_SESSION["userToken"];
$user_projects_json = read_json($GLOBALS['URL_JSON'] . "$user_token" . "_projects" .".json");
$projectKey = $_REQUEST['dataKey'];
$projectKey = trim($projectKey," ");
//v8fe3m
$backups = $user_projects_json['projects'][$projectKey];
unset($backups);
Since PHP is a strange language, it copies objects. Therefore $backups is a copy of $user_projects_json['projects'][$projectKey].
$backups = $user_projects_json['projects'][$projectKey];
unset($backups); //You are unsetting a very new object.
You can do
$backups = &$user_projects_json['projects'][$projectKey];
unset($backups); //You are unsetting a reference that refers to your object.
This way $backups are referring to your original object, thus unsetting what you need. I saw someone did it in the comments, but there were no explanation, unsetting without creating a new object.
First use $arrayFromJson = json_decode($yourJsonObject, true);, then you can use standard PHP array functions such as:
unset($arrayFromJson['v8fe3m']);

Laravel Query to select list entry in JSON field

I'm storing dynamic data in a MySQL JSON field using Laravel v6.11.0, nova v2.9.3 and nova-flexible-content v0.1.13. The data stored looks similar to this:
[
{
"layout": "source",
"key": "5ce8e0a877487fe5",
"attributes": {
"value": "342",
"unit": "USD",
"language": "en",
"url": "http:\\/\\/google.com",
"authority": "google.com",
"entry_date": "2020-01-21",
"date": "2019-12-21"
}
},
{
"layout": "source",
"key": "a82393ce016e8c14",
"attributes": {
"value": "444",
"unit": "USD",
"language": "en",
"entry_date": "2020-01-21",
"url": "https:\\/\\/google.com",
"authority": "TEST",
"date": "2020-01-20"
}
}
]
I was wondering if it's possible to build a Laravel Query to select the second entry based on the authority entry? Criteria are:
url should contain google.com AND
authority shouldn't be google.com
I've found https://laravel.com/docs/5.8/queries#json-where-clauses, but am struggling to put the right query together. Maybe someone could give me some pointers on how to do it? Thank you
You may refer to this discussion on Laracast
$data = App\YourModel::whereRaw('JSON_CONTAINS(body->"$[*].attributes.url", "\"https://google.com\"")')
->orWhereRaw('JSON_CONTAINS(body->"$[*].id", "\"http://google.com\"")')
->whereRaw('not JSON_CONTAINS(body->"$[*].attributes.authority", "\"google.com\"")')
->get();
foreach ($data as $key => $row) {
$bodyArr = json_decode($row->body);
foreach ($bodyArr as $item) {
if ((preg_match("/(http:\/\/www\.|https?:\/\/google.com)/i",$item->attributes->url)) && (strpos($item->attributes->authority, 'google.com') === false)) {
dump($item);
// YOUR CODE GOES HERE
}
}
}

Displaying nested json in laravel 5.2

I have a nested json file
{
"event_type": "INCOMING_BTC",
"event_uid": "5515c5601f7b3",
"datetime": "2015-03-27 21:02:37",
"resources": [
{
"resource_type": "transaction",
"resource": {
"id": 105062,
"datetime": "2015-03-27 21:02:23",
"description": "Money from Xapo Tip",
"order_type": "payment_received",
"from": {
"type": "btc_address",
"id": "1AqF787aPHgPRZ81kdQSeEwW46yjyrAaxR"
},
"to": {
"destination_type": "btc_address",
"destination_id": "1N65Bz88zKUDPKhUUsx8f9Qwsuo96Hqz7S",
"to_account": 1276
},
"generic_type": "credit",
"amount": "0.0000001",
"currency": "BTC",
"status": "completed",
"txConfidence": 1,
"rejection_reason": null,
"notes": null,
"base_currency": "USD",
"exchange_rate": null,
"exchange_amount": null
}
},
{
"resource_type": "address",
"resource": {
"id": "1N65Bz88zKUDPKhUUsx8f9Qwsuo96Hqz7S",
"address": "1N65Bz88zKUDPKhUUsx8f9Qwsuo96Hqz7S",
"meta_data": null,
"label": null,
"total_received": "0.00000350",
"created_at": "2015-03-08 14:50:59",
"address_type": "multisig",
"id_account": "1276"
}
}
]
}
And I have saved this file in public folder with name xapojson.txt
In my routes file I have done json_decode to decode this data to a variable 'transaction' and passed it to view
Route::get('/', function () {
$transaction = json_decode(file_get_contents('xapojson.txt'));
return view('transaction', compact('transaction'));
});
Now in transaction view I have to display the data from this nested json.
I have tried out lots of variation and searched on google and stackoverflow but nothing worked.
I found this somewhat helpful Check this out. But it also do not get into more nesting.
In the view I have to display these datas:-
resources[0]->resource->from->type
resources[0]->resource->id
resources[0]->resource->from->id
resources[0]->resource->status
resources[0]->resource->amount
resources[0]->resource->currency
resources[0]->resource->to->destination_id
datetime
Please help me on displaying the above fields.
Try using
$transaction = json_decode(file_get_contents('xapojson.txt'), true);
Well when I made this code work in simple php, I extracted the data by
$xapo_json = file_get_contents('xapojson.txt');
$xapo_json_decoded = json_decode($xapo_json);
$from_type = $xapo_json_decoded->resources[0]->resource->from->type;
$transacid = $xapo_json_decoded->resources[0]->resource->id;
$from = $xapo_json_decoded->resources[0]->resource->from->id;
$status = $xapo_json_decoded->resources[0]->resource->status;
$amount = $xapo_json_decoded->resources[0]->resource->amount;
$currency = $xapo_json_decoded->resources[0]->resource->currency;
$to = $xapo_json_decoded->resources[0]->resource->to->destination_id;
$datetime = $xapo_json_decoded->datetime;
Then in the routes file i changed
return view('transaction', compact('transaction'));
to
return View::make('transaction')->with('transaction',$transaction);
And in view I used this
{{ $transaction->resources[0]->resource->from->id }}
Voila, It works
you can do it with the below code ( am taking div as example you can change it to table or whatever
#foreach($transaction->resources as $resource)
#if(is_set($resource->from))
<div>{{$resource->from->type}}</div>
#endif
<div>{{$resource->id}}</div>
#if(is_set($resource->from))
<div>{{$resource->from->id}}</div>
#endif
<div>{{$resource->status}}</div>
<div>{{$resource->amount}}</div>
<div>{{$resource->currency}}</div>
<div>{{$resource->to->destination_id}}</div>
#endforeach

Looping over nested arrays below keys

Ok, so that title might be a little misleading, but I'm not quite sure what i'm describing, so here goes.
I have the following JSON :
{
"lastModified": 1368517749000,
"name": "Requiem Paradisum",
"realm": "Chamber of Aspects",
"battlegroup": "Misery",
"level": 25,
"side": 1,
"achievementPoints": 1710,
"emblem": {
"icon": 126,
"iconColor": "ffdfa55a",
"border": 3,
"borderColor": "ff0f1415",
"backgroundColor": "ff232323"
},
"news": [
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368482100000,
"itemId": 91781
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368477900000,
"itemId": 87209
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368475800000,
"itemId": 86880
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91781
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91779
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475320000,
"itemId": 91779
},
{
"type": "playerAchievement",
"character": "Osmoses",
"timestamp": 1368470700000,
"achievement": {
"id": 6193,
"title": "Level 90",
"points": 10,
"description": "Reach level 90.",
"rewardItems": [
{
"id": 87764,
"name": "Serpent's Heart Firework",
"icon": "inv_misc_missilelarge_green",
"quality": 1,
"itemLevel": 1,
"tooltipParams": {
},
"stats": [
],
"armor": 0
}
],
"icon": "achievement_level_90",
"criteria": [
],
"accountWide": false,
"factionId": 2
}
},
Basically i need to loop over everything in "news" and output it.
What I can't figure out how to parse it correctly :
A : without specifying key numbers and
B : when it gets to a key that then contains further keys and further arrays under those keys i'm at a loss. (E.g. the "player achievement" key)
I appreciate I'm probably being a bit newbie here and could quite possibly be on page 1 of "php for dummies" but i swear I've googled it to death!
See if this approach could fit. Be sure your JSON array is properly formatted though.
$test = the_json_array;
$array = json_decode($test,true);
function recursive($array) {
foreach($array as $key => $value) {
if (!is_array($value)) echo $key.":".$value."<br/>";
else recursive($value);
}
}
recursive($array);
SEE json_decode
Dont forget to give second argument as TRUE otherwise it will return object
and try something like this
$json = 'your json'
$json_array = json_decode($json,true);
$news = $json_array['news'];
foreach($news as $value)
{
print_r($value);
}
I think for your purpose you should have look at array_walk_recursive
function printResult($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($news, 'printResult');
yo need to do json_decode('your-jason', True) it will convert your Json string to Array.
Json_decode for more understanding
if you don't specify TRUE in jason_decode function then it will return php object
Hope answer the question. regards

Categories