Laravel Query to select list entry in JSON field - php

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
}
}
}

Related

How to replace JSON key without losing its value and position using PHP

This is the JSON
{
"table-name": "Kiwi",
"created-on": "November 20, 2021",
"columns": {
"Info": {
"type": "longtext",
"extra": ""
},
"Status": {
"type": "droplist",
"extra": ""
},
"Task": {
"type": "text",
"extra": ""
}
},
"data": [
{
"Name": "Team Reports",
"Info": "Submitting marketing materials reports",
"Status": "Completed"
},
{
"Name": "Fabia HR",
"Info": "Brian asking for a report",
"Status": "Pending"
},
{
"Name": "Fabia",
"Info": "Meeting with CEO #cafe 9:00",
"Status": "Cancelled"
}
]
}
And I was trying to achieve to rename the "Info" into "Description" without losing its value and array position. I'm not very familiar with array_replace , that seems my code is not working. Please share some codes, it will be much appreciated.
Here my PHP code I tried
<?PHP
$jsn = file_get_contents('./test.json');
$arr = json_decode($jsn, true);
$newArray= [];
foreach($arr['data'] as $row){
$row['Description'] = $row['Info'];
array_push($newArray, $row);
}
//print_r($newArray);
array_replace($arr['data'],$newArray);
echo json_encode($arr, JSON_PRETTY_PRINT);
Thank you so much for your attention and advance help. It will really gonna save me some time. Noob here and I'm still learning things about PHP and JSON

JSON Post PHP (TypeForm)

I have never used JSON before so apologies if this is a simple request.
I have a webhook setup that sends me a JSON Post (Example Below) - I want to extract the two answers from this "text":"250252" & {"label":"CE"}
{
"event_id": "1",
"event_type": "form_response",
"form_response": {
"form_id": "VpWTMQ",
"token": "1",
"submitted_at": "2018-05-22T14:11:56Z",
"definition": {
"id": "VpWTMQ",
"title": "SS - Skill Change",
"fields": [
{
"id": "kUbaN0JdLDz8",
"title": "Please enter your ID",
"type": "short_text",
"ref": "9ac66945-899b-448d-859f-70562310ee5d",
"allow_multiple_selections": false,
"allow_other_choice": false
},
{
"id": "JQD4ksDpjlln",
"title": "Please select the skill required",
"type": "multiple_choice",
"ref": "a24e6b58-f388-4ea9-9853-75f69e5ca337",
"allow_multiple_selections": false,
"allow_other_choice": false
}
]
},
"answers": [
{
"type": "text",
"text": "250252",
"field": {
"id": "kUbaN0JdLDz8",
"type": "short_text"
}
},
{
"type": "choice",
"choice": {
"label": "CE"
},
"field": {
"id": "JQD4ksDpjlln",
"type": "multiple_choice"
}
}
]
}
}
I have this currently in my PHP file:
$data = json_decode(file_get_contents('php://input'));
$ID = $data->{"text"};
$Skill = $data->{"label"};
This does not work and all I get is null - Any help would really be appreciated, Thank You.
You need to look at the JSON object you're receiving to know the structure of the object you're receiving after using json_decode, what you're trying to get is in $data->form_response->answers, So you can have a variable for easier access:
$answers = $data->form_response->answers;
remember $answers is an array
So to achieve what you're trying to get, you can do:
$data = json_decode(file_get_contents('php://input'));
$answers = $data->form_response->answers;
$ID = $answers[0]->text;
$Skill = $answers[1]->choice->label;

ElasticSearch php sdk simple query not working

this is my first question here, I am having a problem with a simple elasticsearch query made throught the php sdk, json example:
{
"_id": "event:5569fbbdddc85",
"_type": "event",
"videos": {},
"status": "published",
"owner": {
"firstname": "Patricio",
"lastname": "",
"profilepicture": "http://pbs.twimg.com/profile_images/581193413426544640/Q5aqMmPk_normal.jpg",
"_id": "twitter:2383339241",
"_type": "user",
"updated": 1433008088365,
"created": 1428439794713
},
"max_age": "18",
"min_age": "18",
"max_invites": "5",
"min_invites": "2",
"updated": 1433009134942,
"created": 1433009134942
}
What I need to do is a filter by owner._id and I am doing this:
$params['index'] = 'default';
$params['type'] = 'event';
$params['size'] = $limit;
$params['from'] = $from;
$params['body']['query']['match']['owner._id'] = $userId;
// elasticsearch search query
$res = \Es::search($params);
the result is no filter. All the events in database are comming back.
I am following exactly the docs, but with no results, obviously I am missing something
Thanks!
You need your _id field to be not_analyzed or analyzed with the keyword analyzer so that, when indexed by ES, to stay unchanged.
Also, for a query like yours, for _id it is best to use a filter of type term. I am no php developer, but from ES point of view it should look like this:
"_id": {
"type": "string",
"index": "not_analyzed"
}
And the query should be of this form, for _id:
"query": {
"filtered": {
"filter": {
"term": {
"owner._id": "twitter:2383339242"
}
}
}
}

Pushing object to nested JSON using PHP?

In the following JSON object, I have two dummy products and a nested group of reviews that are siblings to one another:
product.json
[
{
"name": "Dodecahedron",
"price": 2.95,
"description": "This gem is awesome and has 10 sides.",
"images": [
{
"full": "dodecahedron-01-full.jpg",
"thumb": "dodecahedron-01-thumb.jpg"
}
],
"reviews": [
{
"stars": 5,
"body": "I love this product!",
"author": "joe#thomas.com"
},
{
"stars": 1,
"body": "This product sucks",
"author": "tim#hater.com"
}
]
},
{
"name": "Hectahedron",
"price": 8.95,
"description": "Wonderful 6-sided gem that will please all.",
"images": [
{
"full": "hectahedron-01-full.jpg",
"thumb": "hectahedron-01-thumb.jpg"
}
],
"reviews": [
{
"stars": 4,
"body": "product is awesome, seriously!",
"author": "james#crazy.com"
},
{
"stars": 2,
"body": "Seriously sucks, would give 0 if i could",
"author": "john#hater.com"
}
]
}
]
I am using AngularJS to send the newly created JS review object from an HTML form to PHP. But how in PHP do you push this review data to become a sibling IN "reviews" AND target the exact product it should be in? I'm very new to PHP and would greatly appreciate your guidance!
If I understand what you are asking, here you need to use the json_decode() function:
$productsRreviews = json_decode($_POST['reviews'], true);
This will give you a PHP associative array that you can process to do whatever you need to do. For instance:
foreach ($productsReviews as $productReviews) {
$name = $productReviews['name'];
$price = $productReviews['price'];
$reviews = $productReviews['reviews'];
foreach ($reviews as $review) {
$stars = $review['stars'];
...
}
}
Hope that helps!

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