Parsing json key value in PHP (multidimensional array) - php

By now I think I 'tried' just about all of the suggested ways to parse the value of one or more keys from a POST response. I've been able to boil it down a little but I'd super appreciate any help someone would be willing to give. My goal is to retrieve the value of the "id" and "campaign_id" keys (or any other key value for that matter). Needless to say I'm at a beginners level ˆ_ˆ
here we go..
$contents = ($this->response);
$enc = ($contents);
results into:
Array ( [0] => [ { "url": "http://www.aguabenito.com", "name": "Bikinis - New arrivals", "prefix": "AGUA", "notes": "", "updated_at": "2017-01-14 16:26:35", "created_at": "2017-01-14 16:26:35", "id": 4609 }, [], [ { "id": 3531, "url_code": "R0uvzO", "alias": null, "campaign_id": 4609, "paidchannel_id": 104, "deleted_at": null, "created_at": "2017-01-14 16:26:35", "updated_at": "2017-01-14 16:26:35" } ] ] )
and then..
for ($i = 0; $i < count($enc); ++$i) {
print $enc[$i];
}
results into:
[
{
"url": "http://www.aguabenito.com",
"name": "Bikinis - New arrivals",
"prefix": "AGUA",
"notes": "",
"updated_at": "2017-01-14 16:26:35",
"created_at": "2017-01-14 16:26:35",
"id": 4609
},
[],
[
{
"id": 3531,
"url_code": "R0uvzO",
"alias": null,
"campaign_id": 4609,
"paidchannel_id": 104,
"deleted_at": null,
"created_at": "2017-01-14 16:26:35",
"updated_at": "2017-01-14 16:26:35"
}
]
I'm afraid to say that I'm just going around in circles from here onwards. When I try to get any of the values I keep getting Illegal string offset or Undefined index errors. Really hoping to learn what I'm doing wrong and how I should go about retrieving the value of one or more of these keys.
Hoping to achieve something in the lines of:
$campaign_id = '4609';
$first_urlcode = 'R0uvzO';
$first_urlcode_id = '3531';
$second_urlcode = 'abc123';
$second_urlcode_id = '1234';

Thanks #EatPienutButter for helping me out!!
This got me walking straight again )))))
$enc = json_decode($contents[0], true);
$campaignid = ($enc[0]['id']);
$first_urlcode = ($enc[2][0]['url_code']);
$first_urlcode_id = ($enc[2][0]['id']);

Related

Merge 2 arrays based on a common element

So I have a Laravel controller that is pulling in 2 arrays.
Array 1:
[
{
"id":1,
"created_at":null,
"updated_at":null,
"name":"The Darkroom",
"description":"This is the room your parents warned you about",
"image":"https:\/\/images.unsplash.com\/photo-1579662908513-50e1433a258a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1234&q=80",
"is_private":"0"
},{
"id":2,
"created_at":null,
"updated_at":null,
"name":"Smoking & Cigars",
"description":"Time to light up and enjoy a cigar!",
"image":"https:\/\/images.unsplash.com\/photo-1617850136763-06bc0a9a089c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2000&q=80",
"is_private":"0"
},{
"id":3,
"created_at":null,
"updated_at":null,
"name":"Humiliation",
"description":"today is the day you are going to be exposed",
"image":"https:\/\/images.unsplash.com\/photo-1571570261702-3d23956fa32e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2600&q=80",
"is_private":"1"
},{
"id":4,
"created_at":null,
"updated_at":null,
"name":"Financial Domination",
"description":"hand over your cash and say thank you Sir!",
"image":"https:\/\/images.unsplash.com\/photo-1526304640581-d334cdbbf45e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80",
"is_private":"0"
},{"id":5,"created_at":null,"updated_at":null,"name":"Pups & Handlers","description":"Woof, woof, bark, sit","image":"https:\/\/images.unsplash.com\/photo-1506939754500-f27bc71fccd4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80","is_private":"1"}]
Array 2:
{"channels":{"presence-chat.1":{"user_count":1},"presence-chat.4":{"user_count":1}}}
Final Array should look like this:
[
{
"id":1
"other data in the first array"
"user_count": 1
}
]
What I NEED to do inside my controller is merge the data together into a single array. So ideally, take the second array, match up the chat.ID with the ID of the first array and add in user_count to it... well you get what I mean.
I Have NEVER done this before so I have NO IDEA how best to go about this. Any help would be forever appreciated!
Here you go, this assumes that presence-chat.4 means channel with the id of 4:
<?php
$json1 = '[{"id":1,"created_at":null,"updated_at":null,"name":"The Darkroom","description":"This is the room your parents warned you about","image":"https:\/\/images.unsplash.com\/photo-1579662908513-50e1433a258a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1234&q=80","is_private":"0"},{"id":2,"created_at":null,"updated_at":null,"name":"Smoking & Cigars","description":"Time to light up and enjoy a cigar!","image":"https:\/\/images.unsplash.com\/photo-1617850136763-06bc0a9a089c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2000&q=80","is_private":"0"},{"id":3,"created_at":null,"updated_at":null,"name":"Humiliation","description":"today is the day you are going to be exposed","image":"https:\/\/images.unsplash.com\/photo-1571570261702-3d23956fa32e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2600&q=80","is_private":"1"},{"id":4,"created_at":null,"updated_at":null,"name":"Financial Domination","description":"hand over your cash and say thank you Sir!","image":"https:\/\/images.unsplash.com\/photo-1526304640581-d334cdbbf45e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80","is_private":"0"},{"id":5,"created_at":null,"updated_at":null,"name":"Pups & Handlers","description":"Woof, woof, bark, sit","image":"https:\/\/images.unsplash.com\/photo-1506939754500-f27bc71fccd4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80","is_private":"1"}]';
$json2 = '{"channels":{"presence-chat.1":{"user_count":1},"presence-chat.4":{"user_count":1}}}';
// convert the json into php arrays
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
// we extract the user_counts from the second array
// and make the index of a new array the channel id with value user_count
$channel_counts = [];
foreach ($array2['channels'] as $chan_name => $count) {
$channel_id = explode('.', $chan_name)[1];
$user_count = $count['user_count'];
$channel_counts[$channel_id] = $user_count;
}
// we pass this array by reference as we are modifying it
foreach ($array1 as &$channel) {
$id = $channel['id'];
if (isset($channel_counts[$id]))
$channel['user_count'] = $channel_counts[$id];
else
$channel['user_count'] = 0;
}
unset($channel);
$final_json = json_encode($array1, JSON_PRETTY_PRINT);
echo $final_json;
Which results in:
[
{
"id": 1,
"created_at": null,
"updated_at": null,
"name": "The Darkroom",
"description": "This is the room your parents warned you about",
"image": "https:\/\/images.unsplash.com\/photo-1579662908513-50e1433a258a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1234&q=80",
"is_private": "0",
"user_count": 1
},
{
"id": 2,
"created_at": null,
"updated_at": null,
"name": "Smoking & Cigars",
"description": "Time to light up and enjoy a cigar!",
"image": "https:\/\/images.unsplash.com\/photo-1617850136763-06bc0a9a089c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2000&q=80",
"is_private": "0",
"user_count": 0
},
{
"id": 3,
"created_at": null,
"updated_at": null,
"name": "Humiliation",
"description": "today is the day you are going to be exposed",
"image": "https:\/\/images.unsplash.com\/photo-1571570261702-3d23956fa32e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2600&q=80",
"is_private": "1",
"user_count": 0
},
{
"id": 4,
"created_at": null,
"updated_at": null,
"name": "Financial Domination",
"description": "hand over your cash and say thank you Sir!",
"image": "https:\/\/images.unsplash.com\/photo-1526304640581-d334cdbbf45e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80",
"is_private": "0",
"user_count": 1
}, ...snip
]

Getting Duplicate Data on Response On Laravel Eloquent

I am new in laravel in php. So it might be very silly mistake. I have song table and song categories table. I am trying to fetch all category with their respective songs. I have implemented larvel eloquent one to many relationship between song category and song.
Here is my code of fetching data:
public function getSongCategoriesWithSongs(){
$json_array = array();
$song_categories = SongCategory::all();
foreach ($song_categories as $item) {
# code...
$json = [];
$json['category'] = $item;
$json['songs'] = $item->songs;
array_push($json_array,$json);
}
return $json_array;
}
Here is response:
[{
"category": {
"id": 1,
"title": "Rock",
"created_at": "2020-12-20T02:58:32.000000Z",
"updated_at": "2020-12-20T02:58:32.000000Z",
"songs": [{
"id": 1,
"title": "Mere Mehboob",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/2u039f-a.akamaihd.net\/downloads\/ringtones\/files\/mp3\/mere-mehboob-qayamat-hogi-52150.mp3",
"created_at": "2020-12-20T13:26:30.000000Z",
"updated_at": "2020-12-20T13:26:30.000000Z"
}, {
"id": 2,
"title": " Taaron Ke Shehar",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/TaaronKeSheharRingtoneByNehaKakkarJubinNautiyal2145436126.mp3",
"created_at": null,
"updated_at": null
}, {
"id": 3,
"title": "Bewafa Tera Masoom Chehra",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/BewafaTeraMasoomChehraRingtoneByJubinNautiyal352778308.mp3",
"created_at": null,
"updated_at": null
}]
}
}, {
"songs": [{
"id": 1,
"title": "Mere Mehboob",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/2u039f-a.akamaihd.net\/downloads\/ringtones\/files\/mp3\/mere-mehboob-qayamat-hogi-52150.mp3",
"created_at": "2020-12-20T13:26:30.000000Z",
"updated_at": "2020-12-20T13:26:30.000000Z"
}, {
"id": 2,
"title": " Taaron Ke Shehar",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/TaaronKeSheharRingtoneByNehaKakkarJubinNautiyal2145436126.mp3",
"created_at": null,
"updated_at": null
}, {
"id": 3,
"title": "Bewafa Tera Masoom Chehra",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/BewafaTeraMasoomChehraRingtoneByJubinNautiyal352778308.mp3",
"created_at": null,
"updated_at": null
}]
}, {
"category": {
"id": 2,
"title": "Soft",
"created_at": null,
"updated_at": null,
"songs": []
}
}, {
"songs": []
}]
As you can see songs get repeated.
UPDATE
Solved using eager loading
public function getSongCategoriesWithSongs(){
return SongCategory::with('songs')->get();
}
But don't know why the foreach method not working.
Try this code
public function getSongCategoriesWithSongs(){
$json_array = array();
$song_categories = SongCategory::all();
foreach ($song_categories as $item) {
$json_array[] = ['category' => $item, 'songs' => $item->songs] ;
}
return $json_array;
}
The problem is that you assign the same relation twice.
Each SongCategory already has a collection of songs inside.
So in your foreach block, you assign a category with $json['category'] => $item which will load all related songs and pass them to the final JSON object. And you duplicate this by passing the next item $json['songs'] = $item->songs to the same array. Default Laravel behavior will be to fetch all related objects and transform them into JSON.
I would suggest you to use Laravel resources to return JSON objects with exact shapes: API Resources.
You can fix your code block without eager loading by removing $json['songs'] = $item->songs assignment.
Eager loading works because you passed all your objects only once.

Delete unwanted data from api result

I have a project in laravel which has API. I'm asking the API for posts(I call them recommendation).
Now my api response look like this -
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
...
...
...
All is good but I don't wanna likes_count to be in the result. It is a relation method. I get from it all I need. It is if the user liked this post. And it is is_liked in the result . but likes_count automatically added to the response .
if($item->likesCount->contains($user->id)){
$item['is_liked']='true';
}
I tried delete it with
foreach ($recommendations as $item) {
unset($item['likes_count']);
}
But it doesn't do it.
I think the problem is how you are referencing the object data structure. You are attempting to unset() something that doesn't exist so no error is thrown but the likes_count isn't getting removed either.
Here's your code example (fixed and modified for demonstration):
<?php
$apiResult = <<<eod
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
},
{
"id": 4,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
]
}
}
eod;
$result = json_decode($apiResult);
$data = $result->data->data;
var_dump($data);
// This should remove the likes_count array from the $result structure.
foreach ($data as &$item) {
unset($item->likes_count);
}
var_dump($data);
A quick way would be to make that 'attribute' (relation) hidden:
$recommendations->makeHidden('likes_count');
Though I am not sure how you are building your response.

PHP - Retrieve JSON data and values [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm new into PHP and JSON and I have a problem, I want to retrieve a item and value from a JSON:
{
"status": true,
"webhook_type": 100,
"data": {
"product": {
"id": "lSEADIQ",
"attachment_id": null,
"title": "Registration",
"description": null,
"image": null,
"unlisted": false,
"type": "service",
"price": 1,
"currency": "EUR",
"email": {
"enabled": false
},
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 1
},
"confirmations": 1,
"custom_fields": [
{
"name": "Forum username",
"type": "text",
"required": true
}
],
"gateways": [
"Bitcoin"
],
"webhook_urls": [],
"dynamic_url": "",
"position": null,
"created_at": "2018-10-01 12:51:12",
"updated_at": "2018-10-01 12:55:46",
"stock": 9223372036854776000,
"accounts": []
},
"order": {
"id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
"created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
"paid_at": null,
"transaction_id": null,
"confirmations": 1,
"required_confirmations": 3,
"received_amount": 0,
"crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
"crypto_amount": "0.4815",
"quantity": 1,
"price": 19.99,
"currency": "EUR",
"exchange_rate": "1.21",
"gateway": "BTC",
"email": "webhook#site.gg",
"ip_address": "123.456.789.111",
"agent": {
"geo": {
"ip": "214.44.18.6",
"iso_code": "US",
"country": "United States"
},
"data": {
"is_mobile": false,
"is_table": false,
"is_desktop": true,
"browser": {
"name": "Chrome",
"version": "63.0.3239.132"
}
}
},
"custom_fields": [
{
"name": "user_id",
"value": 184191
}
],
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
}
}
}
I want to retrieve items from data -> order, for example "id" or "ip_address".
Thank you for read this, I hope someone can help me in this, because I'm lost, I started to code very recently and I'm trying to learn a lot.
Regards!
Where test.json is the json you uploaded, place it in a file named test.json and ensure its placed in the same directory.
<?php
$load = file_get_contents("test.json") or die("JSON load failed");
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n";
?>
Gives:
123.456.789.111
My answer reads the JSON from a file as were it dumped directly in your code, which indeed it could be, it would make the code less readable and your file more messy.
If you dont want to place the file in the same directory, simply specify the full file path. E.g. file_get_contents("this/dir/here/test.json");
You can read about how json_decode works here, its essential we pass it the true parameter to make our arrays associative.
You can extract your need array from JSON data. You can use a loop too to read all your data inside the order array.
$array = json_decode($json, true);
$verbose = $array['data'];
$orderArray = $verbose['order'];
print_r($orderArray);
echo $orderArray['id'];
echo $orderArray['ip_address'];

Merge two objects, while one is inside of an array

I need to merge 2 objects using PHP (Laravel) one of them is in an array, the other is a plain object, but also contains a nested object, is there any simple way to do it?
Edit: The result should be a single object
[
{
"id": 1,
"release_date": "1998",
"license_plate": "098HBV",
"state_id": 1,
"type_id": 7,
"created_at": "2016-11-18 11:39:19",
"updated_at": "2016-11-18 11:39:19",
"deleted_at": null
}
]
and
{
"id": 1,
"parent_id": null,
"name": "Chrysler",
"state_id": 1,
"type_id": 1,
"created_at": "2016-11-18 11:39:10",
"updated_at": "2016-11-18 11:39:10",
"deleted_at": null,
"pivot": {
"vehicle_id": 1,
"brand_id": 1
}
}
Desired output should be:
{
"id": 1,
"release_date": "1998",
"license_plate": "098HBV",
"name": "Chrysler",
}
It has to be something similar, otherwise it would break a lot of JavaScript code connected to the first object.
<?php
//Merge the two as an array
$merged = array_merge($array,(array)$object);
//As an object
$merged = (object)$merged;

Categories