Sort array by specific value with usort - php

I know that similar threads exist, and I have tried to understand and read them all, but I'm not getting anywhere.
Problem: I'd like to output all the films directed by Stanley Kubrick and I want the movies to be listed in descending order by year of release.
The output of the films works, but I can't sort them.
"crew": [
{
"id": 45966,
"department": "Camera",
"original_language": "en",
"original_title": "Day of the Fight",
"job": "Director of Photography",
"overview": "American short subject documentary film in black-and-white, which is notable as the first picture directed by Stanley Kubrick. Kubrick financed the film himself, and it is based on an earlier photo feature he had done as a photographer for Look magazine in 1949. 'Day of the Fight' shows Irish-American middleweight boxer Walter Cartier during the height of his career, on the day of a fight with black middleweight Bobby James, which took place on April 17, 1950.",
"vote_count": 69,
"video": false,
"poster_path": "/4caX3IZkf7n2QCbxaJO3hyn0SCm.jpg",
"backdrop_path": "/lt1Lan9bmG29JjqaMad5tkRpCHJ.jpg",
"title": "Day of the Fight",
"popularity": 4.701,
"genre_ids": [
99
],
"vote_average": 5.9,
"adult": false,
"release_date": "1951-04-26",
"credit_id": "55d0b196c3a3681bff007bde"
},
{
"id": 10165,
"department": "Camera",
"original_language": "en",
"original_title": "Fear and Desire",
"job": "Director of Photography",
"overview": "After their airplane crashes behind enemy lines, four soldiers must survive and try to find a way back to their battalion. However, when they come across a local peasant girl the horrors of war quickly become apparent.",
"vote_count": 254,
"video": false,
"poster_path": "/oiN9OUOGbVywUHjto30AfLpnIJ7.jpg",
"backdrop_path": "/e3o0Dwlzzpd4kJpOOJgVyMstnII.jpg",
"title": "Fear and Desire",
"popularity": 6.052,
"genre_ids": [
18,
10752
],
"vote_average": 5.5,
"adult": false,
"release_date": "1953-04-01",
"credit_id": "55d0b9c392514131a5007a4c"
},
{
"id": 45314,
"department": "Camera",
"original_language": "en",
"original_title": "The Seafarers",
"job": "Director of Photography",
"overview": "Acclaimed director Stanley Kubrick's first film made in color. The documentary focuses on the benefits of membership to the Seafarers International Union.",
"vote_count": 44,
"video": false,
"release_date": "1953-10-15",
"vote_average": 4.7,
"title": "The Seafarers",
"popularity": 3.009,
"genre_ids": [
99
],
"backdrop_path": null,
"adult": false,
"poster_path": "/nSucFIAQ5CowEE1WZ87mz3OsbQ1.jpg",
"credit_id": "55d0cae1c3a36877570014d2"
},
{
"id": 975,
"department": "Camera",
"original_language": "en",
"original_title": "Paths of Glory",
"job": "Additional Photography",
"overview": "A commanding officer defends three scapegoats on trial for a failed offensive that occurred within the French Army in 1916.",
"vote_count": 1613,
"video": false,
"poster_path": "/peblNaHOiTR8DACYyUWsJHhK6GP.jpg",
"backdrop_path": "/yFykLiFuBU6CrGWr2hLP0ttbQ2i.jpg",
"title": "Paths of Glory",
"popularity": 11.573,
"genre_ids": [
18,
10752
],
"vote_average": 8.3,
"adult": false,
"release_date": "1957-09-18",
"credit_id": "5706f1259251412b1400065c"
},
{
"id": 45970,
"department": "Camera",
"original_language": "en",
"original_title": "Flying Padre",
"job": "Director of Photography",
"overview": "Two days in the life of priest Father Fred Stadtmuller whose New Mexico parish is so large he can only spread goodness and light among his flock with the aid of a mono-plane. The priestly pilot is seen dashing from one province to the next at the helm of his trusty Piper Club administering guidance (his plane, the Flying Padre) to unruly children, sermonizing at funerals and flying a sickly child and its mother to a hospital.",
"vote_count": 56,
"video": false,
"release_date": "1951-03-23",
"vote_average": 5.2,
"title": "Flying Padre",
"popularity": 4.033,
"genre_ids": [
99
],
"backdrop_path": "/5HisBYhc75h0DYXSMJWN1eFaxse.jpg",
"adult": false,
"poster_path": "/5aog5qVlMFakpogT1Nar9Z7gqq4.jpg",
"credit_id": "5e94991dccb15f001571103c"
},
{
"id": 10056,
"department": "Camera",
"original_language": "en",
"original_title": "Killer's Kiss",
"job": "Director of Photography",
"overview": "The film revolves around Davey Gordon, a 29 year old welterweight New York boxer in the end of his career, and his relationship with a dancer and her violent employer.",
"vote_count": 283,
"video": false,
"poster_path": "/jc5EjvQywJqS8Xm0RWMoblJvCM6.jpg",
"backdrop_path": "/6VhN0ScAA8VgK3qyRnZ7azD9XEV.jpg",
"title": "Killer's Kiss",
"popularity": 10.353,
"genre_ids": [
80,
18,
53
],
"vote_average": 6.4,
"adult": false,
"release_date": "1955-09-21",
"credit_id": "5e9499448e87020013ce555f"
},
{
"id": 185,
"department": "Directing",
"original_language": "en",
"original_title": "A Clockwork Orange",
"job": "Director",
"overview": "In a near-future Britain, young Alexander DeLarge and his pals get their kicks beating and raping anyone they please. When not destroying the lives of others, Alex swoons to the music of Beethoven. The state, eager to crack down on juvenile crime, gives an incarcerated Alex the option to undergo an invasive procedure that'll rob him of all personal agency. In a time when conscience is a commodity, can Alex change his tune?",
"vote_count": 8571,
"video": false,
"release_date": "1971-12-19",
"vote_average": 8.2,
"title": "A Clockwork Orange",
"popularity": 25.023,
"genre_ids": [
878,
18
],
"backdrop_path": "/keblhZFIZYiWflmURWNHEuS2jqL.jpg",
"adult": false,
"poster_path": "/4sHeTAp65WrSSuc05nRBKddhBxO.jpg",
"credit_id": "52fe4224c3a36847f80071db"
},
My code so far
$data = file_get_contents($url); // put the contents of the file into a variable
$director = json_decode($data); // decode the JSON feed
echo '<pre>';
print_r($director);
foreach ($director->crew as $showDirector) {
if ($showDirector->department == 'Directing') {
usort($showDirector, function ($item1, $item2) {
return $item2['release_date'] <=> $item1['release_date'];
});
echo $showDirector->release_date . ' / ' . $showDirector->title . '<br>';
}
}

usort gets passed the elements from the array exactly as they are. i.e. in this case your array contains objects - therefore you need to do the comparison on the properties of the objects and not as elements in an array.
Instead of comparing the items as array elements like this:
return $item2['release_date'] <=> $item1['release_date']);
...your function should be checking the object properties like this:
usort($showDirector, function ($item1, $item2) {
/* Check the release_date property of the objects passed in */
return $item2->release_date <=> $item1->release_date;
});
Also, you are also trying to sort the array in the wrong place - each time you find a director, you are sorting that single array (and there is only one element so nothing changes).
You need to:
Add all of the required director items into a separate array for sorting
When you have all items for sorting, you sort this array
Then you can loop through this sorted array to process the results, e.g. display them.
See the code below - the steps are commented so you can see what you need to do:
$data = file_get_contents($url); // put the contents of the file into a variable
$director = json_decode($data); // decode the JSON feed
/* 1. Create an array with the items you want to sort */
$directors_to_sort = array();
foreach ($director->crew as $showDirector) {
if ($showDirector->department == 'Directing') {
$directors_to_sort[] = $showDirector;
}
}
/* 2. Now sort those items
note, we compare the object properties instead of trying to use them as arrays */
usort($directors_to_sort, function ($item1, $item2) {
return $item2->release_date <=> $item1->release_date;
});
/* 3. Loop through the sorted array to display them */
foreach ($directors_to_sort as $director_to_display){
echo $director_to_display->release_date . ' / ' . $director_to_display->title . '<br>';
}

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
]

How to get a particular string from and api response?

I have been on a little project of mine now i want to find imdb_id using tmdb_id so for that I have been trying to use the API.
https://api.themoviedb.org/3/tv/67026?api_key=myapikey&append_to_response=external_ids
which brings up the results like this
{
"backdrop_path": "/hcFbIbDzsB9aSSw9VkSGFEl5sGO.jpg",
"created_by": [{
"id": 230174,
"credit_id": "577eb8e5c3a368694a0027ac",
"name": "David Guggenheim",
"gender": 2,
"profile_path": "/hqSydaadHO6EsBIn3BQEzzfxNUY.jpg"
}],
"episode_run_time": [42],
"first_air_date": "2016-09-21",
"genres": [{
"id": 18,
"name": "Drama"
}, {
"id": 10768,
"name": "War & Politics"
}],
"homepage": "https://www.netflix.com/title/80113647",
"id": 67026,
"in_production": false,
"languages": ["en"],
"last_air_date": "2019-06-07",
"last_episode_to_air": {
"air_date": "2019-06-07",
"episode_number": 10,
"id": 1809432,
"name": "#truthorconsequences",
"overview": "On election day, Kirkman turns to his therapist to assuage his conscience about the events -- and his own decisions -- of the momentous prior 36 hours.",
"production_code": "",
"season_number": 3,
"show_id": 67026,
"still_path": "/cpy3uV100RyZuvJN535JLTrj4Nz.jpg",
"vote_average": 7.0,
"vote_count": 1
},
"name": "Designated Survivor",
"next_episode_to_air": null,
"networks": [{
"name": "ABC",
"id": 2,
"logo_path": "/ndAvF4JLsliGreX87jAc9GdjmJY.png",
"origin_country": "US"
}, {
"name": "Netflix",
"id": 213,
"logo_path": "/wwemzKWzjKYJFfCeiB57q3r4Bcm.png",
"origin_country": ""
}],
"number_of_episodes": 53,
"number_of_seasons": 3,
"origin_country": ["US"],
"original_language": "en",
"original_name": "Designated Survivor",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"popularity": 30.031,
"poster_path": "/5R125JAIh1N38pzHp2dRsBpOVNY.jpg",
"production_companies": [{
"id": 28788,
"logo_path": null,
"name": "Genre Films",
"origin_country": "US"
}, {
"id": 19366,
"logo_path": "/vOH8dyQhLK01pg5fYkgiS31jlFm.png",
"name": "ABC Studios",
"origin_country": "US"
}, {
"id": 78984,
"logo_path": null,
"name": "Entertainment 360",
"origin_country": "US"
}],
"seasons": [{
"air_date": "2016-09-20",
"episode_count": 21,
"id": 78328,
"name": "Season 1",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"poster_path": "/1QHlD6z9FnXuuTDVLJnjrtLfVyq.jpg",
"season_number": 1
}, {
"air_date": "2017-09-27",
"episode_count": 22,
"id": 91130,
"name": "Season 2",
"overview": "",
"poster_path": "/z4hdj8cYyqCO9lVBOGm6YZsnMho.jpg",
"season_number": 2
}, {
"air_date": "2019-06-07",
"episode_count": 10,
"id": 122914,
"name": "Season 3",
"overview": "",
"poster_path": "/wn310FWQhjjpHbqsMRBcXr28EHc.jpg",
"season_number": 3
}],
"status": "Canceled",
"type": "Scripted",
"vote_average": 7.2,
"vote_count": 408,
"external_ids": {
"imdb_id": "tt5296406",
"freebase_mid": null,
"freebase_id": null,
"tvdb_id": 311876,
"tvrage_id": 51115,
"facebook_id": "DesignatedSurvivor",
"instagram_id": "designatedsurvivor",
"twitter_id": "DesignatedNFLX"
}
}
So now if I want to get just the IMDb_ID form the external_ids then what code should i use in PHP and store it in a variable.
Thank you very much in advance.
use the json_decode method to treat JSON like a PHP object
$data = 'your JSON object';//raw data as string in $data
$decoded = json_decode($data);//decoded data as PHP object
echo $decoded->external_ids->imdb_id; //access any property you like
hope this helps!!!

How to insert nested array of a multidimensional array into mysql

I have a multidimensional aray that i want to insert into mysql database. Everything works fine but iwant a better solution as the rows repeat itself following the nested array
here is my json
{
"results": [
{
"id": 48728,
"name": "MOVIES AT THE PARK # GIBA GORGE",
"url": "Some URL",
"imageUrl": "Some Path",
"dateCreated": "2018-06-08T09:18:59.717",
"lastModified": "2018-06-26T14:20:45.0214921",
"startDate": "2018-07-28T17:00:00",
"endDate": "2018-07-28T22:00:00",
"venue": {
"id": 0,
"name": "Giba Gorge Mountain Bike Park",
"addressLine1": "110 Stockville Road",
"addressLine2": "",
"latitude": -29.8276051,
"longitude": 30.781735700000013
},
"locality": {
"levelOne": "South Africa",
"levelTwo": "KwaZulu-Natal",
"levelThree": "Clifton Canyon"
},
"organiser": {
"id": 0,
"name": "Ultra Glow SA ",
"phone": "0822603351",
"mobile": "0828927837",
"facebookUrl": "",
"twitterHandle": "",
"hashTag": "UGMOVIES",
"organiserPageUrl": "some url"
},
"categories": [
{
"id": 3,
"name": "Film & Media"
},
{
"id": 12,
"name": "Food & Drink"
}
],
"tickets": [
{
"id": 98655,
"name": "ADULT TICKET",
"soldOut": false,
"provisionallySoldOut": false,
"price": 100,
"salesStart": "2018-06-26T11:52:00",
"salesEnd": "2018-07-28T17:00:00",
"description": "",
"donation": false,
"vendorTicket": false
},
{
"id": 98656,
"name": "UNDER 12",
"soldOut": false,
"provisionallySoldOut": false,
"price": 80,
"salesStart": "2018-06-26T11:53:00",
"salesEnd": "2018-07-28T17:00:00",
"description": "",
"donation": false,
"vendorTicket": false
}
],
"schedules": [
],
"refundFeePayableBy": 0
},
{
"id": 51681,
"name": "ULTRA GLOW COLOUR CRUZ # RIETVLEI ZOO FARM",
"url": "some url",
"imageUrl": "some path",
"dateCreated": "2018-06-26T12:12:07.3",
"lastModified": "2018-06-28T15:22:24.1579751",
"startDate": "2018-08-12T10:00:00",
"endDate": "2018-08-12T14:00:00",
"venue": {
"id": 0,
"name": "Rietvlei Zoo Farm",
"addressLine1": "101 Swartkoppies Road",
"addressLine2": "",
"latitude": -26.3117147,
"longitude": 28.07989120000002
},
"locality": {
"levelOne": "South Africa",
"levelTwo": "Gauteng",
"levelThree": "Johannesburg South"
},
"organiser": {
"id": 0,
"name": " Ultra Glow South Africa",
"phone": "0822603351",
"mobile": "0828927837",
"facebookUrl": "",
"twitterHandle": "",
"hashTag": "",
"organiserPageUrl": "some url"
},
"categories": [
{
"id": 60,
"name": "Trail Running"
},
{
"id": 5,
"name": "Sports & Fitness"
}
],
"tickets": [
{
"id": 98735,
"name": "ADULT EARLY BIRD",
"soldOut": false,
"provisionallySoldOut": false,
"price": 150,
"salesStart": "2018-06-26T12:47:00",
"salesEnd": "2018-08-12T10:00:00",
"description": "",
"donation": false,
"vendorTicket": false
},
{
"id": 98736,
"name": "UNDER 12 - EARLY BIRD",
"soldOut": false,
"provisionallySoldOut": false,
"price": 120,
"salesStart": "2018-06-26T12:47:00",
"salesEnd": "2018-08-12T10:00:00",
"description": "",
"donation": false,
"vendorTicket": false
}
],
"schedules": [
],
"refundFeePayableBy": 0
}
],
"pageSize": 10,
"pages": 1,
"records": 2,
"extras": null,
"message": null,
"statusCode": 0
}
i have tried the following code to insert the relevant datas into database
<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];
$n= sizeof($results);
for($i=0;$i<$n;$i++){
$row=$results[$i];
foreach($row['tickets'] as $key => $value){
$sql="INSERT into
event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketNa me,price)
VALUES('".$row["name"]."','".$row["url"]."','".$row["imageUrl"]."','".$row["dateCreated"]."','".$row["venue"]["name"]."','".$row["venue"]["addressLine1"]."','".$row["venue"]["addressLine2"]."','".$value["name"]."','".$value["price"]."')";
mysqli_query($connect,$sql);
}
}
echo "events data inserted";
?>
This enters the respective datas into my database but because of the nested array tickets with respective keys name and price the same events are being posted twice into my database like MOVIES AT THE PARK # GIBA GORGE for price 100 is one one row and MOVIES AT THE PARK # GIBA GORGE for price 80 on another row ... I have to display these datas in future as part of one event name with their the ticket type and price as a table... do you have any idea on any other way i can make it better, instead of having two rows for same events?
Thanks in advance
for those who have been suggesting me not to use for and foreach loop this is my update code after removing for loop and a single foreach loop and it gives me an error of undefined index of name and price under tickets
<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];
foreach($results as $key => $result){
$sql="INSERT into `event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketName,price) VALUES('".$result["name"]."','".$result["url"]."','".$result["imageUrl"]."','".$result["dateCreated"]."','".$result["venue"]["name"]."','".$result["venue"]["addressLine1"]."','".$result["venue"]["addressLine2"]."','".$result["tickets"]["name"]."','".$result["tickets"]["price"]."')";`
mysqli_query($connect,$sql);
}
echo "events data inserted";
?>
hence i have further updated my code by using two foreach loops, one to ietrate through the top level array "results" and the other to iterate through the nested array "tickets"
<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];
foreach($results as $key => $result){
foreach($result["tickets"] as $k => $v){
$sql="INSERT into event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketName,price) VALUES('".$result["name"]."','".$result["url"]."','".$result["imageUrl"]."','".$result["dateCreated"]."','".$result["venue"]["name"]."','".$result["venue"]["addressLine1"]."','".$result["venue"]["addressLine2"]."','".$v["name"]."','".$v["price"]."')";`
mysqli_query($connect,$sql);
}
}
echo "events data inserted";
?>
that iterates through the nested array so there is nothing wrong in my code now the only problem is i am getting 2 events on my table because of two ticket types adult and children in "tickets" array
so as per many suggestions here i need to create two separate tables for events and tickets i would appreciate if anyone can tell me that how do iconnect these two tables to be able to show the information of my events in html with ticket type and price shown in html table tag thanks in advance
The main reason that is happening is look at the below code :
$row=$results[$i];
foreach($row['tickets'] as $key => $value){
$sql="INSERT into event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketNa me,price) VALUES('".$row["name"]."','".$row["url"]."','".$row["imageUrl"]."','".$row["dateCreated]."','".$row["venue"]["name"]."','".$row["venue"]["addressLine1"]."','".$row["venue"]["addressLine2"]."','".$value["name"]."','".$value["price"]."')";
mysqli_query($connect,$sql);
}
The $row contains your one main entry and $row['tickets'] contains 2 entries and you are using the $row main contents inside the loop for tickets. That is the reason you are getting 2 entries. The best way to cope this is to use a single foreach loop instead of using a for and a foreach.
EDIT:
Actually I would like to suggest to normalize your table by breaking this into 2 tables, one for storing event information and the other for using the ticket information. See the structure below:
event(id,name,url,imageUrl,addressLine1,addressLine2,dateCreated);
event_tickets(id,event_id,ticketName,price,dateCreated);
This will help you maintain the information easily. Also you can modify the code to something like this :
$sql="INSERT into event(name,url,imageUrl,addressLine1,addressLine,2dateCreated) VALUES ('".$row['name']."','".$row['url']."','".$row['imageUrl']."','".$row['venue']['addressLine1']."','".$row['venue']['addressLine2']."','".date('Y-m-d h:i:s')."');"
mysqli_query($connect, $sql);
$event_id = mysqli_insert_id($connect);
And then you can use a foreach to insert the ticket information in the event_tickets table.
Hope this helps
it's because you're using a foreach within a for. You just want a foreach:
foreach ($multiArray as $key => $singleArray) {
//rest of code, replacing $row with $singleArray['key']. E.g. $singleArray['id']
}
update after seeing OP update:
so you would do:
foreach ($results as $row) {
foreach ($row['tickets'] as $ticket) {
//sql
}
}
this should allow you to use $ticket['key'] in your SQL - though I do suggest switch to PDO prepared statements to protect yourself from SQL injection.
Also as other suggested, separating tickets into its own table would be highly advantageous to you.

Laravel structuring JSON response

I am struggling to structure json response in Laravel, here's an example:
{
"0": {
"instagram": [
{
"description": "#trainedacademy taking a break. We will resume for business on Monday 😎 #nickyjanew 🌞",
"time": "Wednesday 25th October",
"image": "https://scontent-lhr3-1.cdninstagram.com/t51.2885-15/s640x640/e15/22794071_716881718510905_8530561994892247040_n.jpg",
"likes": 15,
"comments": 0,
"link": "https://www.instagram.com/p/Baq437_FRav/",
"video": "https://scontent-lhr3-1.cdninstagram.com/t50.2886-16/22831768_291580031330276_8396013842173263872_n.mp4"
},
{
"description": "Jump into a #personaltraining #career! Started college and decided it’s not for you? Want to be a Gym Instructor? Circuit Trainer? Or work towards a career in the Fire Service? Join us Weds night for open enrolment or just get some careers advice from #paulalitherland and #nickyjanew \n#mahdloyouthzone 6:30pm Wednesday 8th November 2017. \nUCAS accredited \nindustry recognised \nExclusive discounts with the Fire Team badge \nFree food box #chiaproteinbar \nWork placements #thegymgroup",
"time": "Sunday 8th October",
"image": "https://scontent-lhr3-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/22277977_106714113419553_5412239854790508544_n.jpg",
"likes": 42,
"comments": 2,
"link": "https://www.instagram.com/p/BZ-WYZJloMY/",
"video": "https://scontent-lhr3-1.cdninstagram.com/t50.2886-16/22831768_291580031330276_8396013842173263872_n.mp4"
},
{
"description": "#trainedacademy #team #mahdloyouthzone preparing marketing material for 2018 enrolments. #oldhamfitness #oldham #practical #learningenhanced #alevels #employability #gymcareer #thegymgroup #chiaproteinbar",
"time": "Friday 6th October",
"image": "https://scontent-lhr3-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/22280199_2265489343466713_511544494877835264_n.jpg",
"likes": 50,
"comments": 0,
"link": "https://www.instagram.com/p/BZ5hLU6FRzr/",
"video": "https://scontent-lhr3-1.cdninstagram.com/t50.2886-16/22831768_291580031330276_8396013842173263872_n.mp4"
},
What I want to do is get rid of the "0": { part of the json. Is that possible?
return response()->json(['count' => $count_instagram, ['instagram' => $instagramArray ]], 200);
You have to use like this:
return response()->json(['count' => $count_instagram, 'instagram' => $instagramArray ], 200);
Instead of
return response()->json(['count' => $count_instagram, ['instagram' => $instagramArray ]], 200);

Remove the {1} from an array of objects

I want my $row->responses object to look like so:
"responses": [
{
"id": 1381822,
"user_id": 45313,
"respondent_name": "JP Pullen",
"response_time": 1424127673,
"is_root_response": true,
"response_tree_id": 1377018,
"project_users_id": 74311,
"display_name": "Mobile 2",
"lft": 1,
"rgt": 2,
"response_read": true,
"body": "Sure it really is was great I purchased choclate at my local grocery store.",
"answers": [ ],
"avatar_url": null,
"mtime": null,
"media_list": [ ]
},
Yet my $row->responses object looks like:
"responses": {
"1": {
"id": 1381825,
"user_id": 45167,
"respondent_name": "First Name Last Name",
"response_time": 1424128177,
"is_root_response": true,
"response_tree_id": 1377021,
"project_users_id": 74312,
"display_name": "SimonSays",
"lft": 3,
"rgt": 4,
"response_read": false,
"body": "What's up!",
"answers": [ ],
"avatar_url": "https:\/\/portalvhds5kcv8nfhdz8zn.blob.core.windows.net\/user-45167\/avatar-50x50",
"mtime": 1420206441,
"media_list": [ ]
}
}
How do you get rid of the stupid {1} in the object. I didn't get it until I had to loop through the objects and unset one of them. I am not a PHP expert. Strongly Typed FTW lol.
foreach($row->responses as $elementKey => $element)
^ That is how I looped through the responses object to unset one:
unset($row->responses{$elementKey});
When arrays are encoded using json_encode() PHP will determine whether it should use array syntax (square brackets) or object syntax (curly brackets). In this case, the first array index is 1 instead of 0 so it can't reliably be encoded as a JavaScript array.
To prevent this from happening, you can use array_values() to renumber the array to be 0-based again:
$row->responses = array_values($row->responses);

Categories