I am trying to iterate over this array in order to take all league values (league_id,name,type etc)
array:1 [▼
"api" => array:2 [▼
"results" => 970
"leagues" => array:970 [▼
0 => array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]
1 => array:13 [▼
"league_id" => 2
"name" => "Premier League"
"type" => "League"
"country" => "England"
"country_code" => "GB"
"season" => 2018
"season_start" => "2018-08-10"
"season_end" => "2019-05-12"
"logo" => "https://media.api-football.com/leagues/2.png"
"flag" => "https://media.api-football.com/flags/gb.svg"
"standings" => 1
"is_current" => 0
]
.......
but until now,with the following code:
$request = json_decode($request->getBody()->getContents(), true);
foreach ($request as $array=>$val) {
foreach ($val['leagues'] as $id) {
dd($id);
}
}
the only thing that i can get is the first array only and not the rest:
array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]
any help?
The dd() function you are calling is killing the execution of your script on your first iteration.
From the Laravel Docs:
The dd function dumps the given variables and ends execution of the script.
If you do not want to halt the execution of your script, use the dump function instead.
Just iterate over it like so:
$request = json_decode($request->getBody()->getContents(), true);
foreach ($request['leagues'] as $id=>$league) {
print_r(compact('id', 'league')); // To see the id and value array
}
Hope this helps,
Related
My aim here is to remove the whole object from the array if "record_type" is null. I should then only be left with data that has a record_type set in the array.
I've looked into the array filter not sure how I target the data within the array "record_type". My only other thought is to import to a database and then SQL query what I want then delete data I've had which is much more overkill.
<pre>
array:36 [▼
0 => array:3 [▼
"type" => "comment"
"line_index" => 0
"text_b64" => "OyBjUGFuZWwgZmlyc3Q6ODguMC4xMiAodXBkYXRlX3RpbWUpOjE2MTg1NDYxNDIgQ3BhbmVsOjpab25lRmlsZTo6VkVSU0lPTjoxLjMgaG9zdG5hbWU6cjExOC5sb24yLm15c2VjdXJlY2xvdWRob3N0LmNvbSBs ▶"
]
1 => array:3 [▼
"line_index" => 1
"text_b64" => "OyBab25lIGZpbGUgZm9yIG9ha3RyZWVkZW50YWxtb3J0aW1lci5jby51aw=="
"type" => "comment"
]
2 => array:3 [▼
"text_b64" => "JFRUTCAxNDQwMA=="
"line_index" => 2
"type" => "control"
]
3 => array:6 [▼
"line_index" => 3
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"record_type" => "SOA"
"ttl" => 30
"type" => "record"
"data_b64" => array:7 [▶]
]
4 => array:6 [▼
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 10
"record_type" => "NS"
"ttl" => 30
"type" => "record"
"data_b64" => array:1 [▶]
]
5 => array:6 [▼
"ttl" => 30
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 11
"record_type" => "NS"
"data_b64" => array:1 [▶]
"type" => "record"
]
</pre>
Goal: only be left with data that has a 'record_type' set (not null) in the array
Solution: use array_filter() on your source array ($arr) and filter for records with 'record_type' != "NS" (assuming "NS" is what you refer to as null, or not set).
<?php
$result = array_filter(
$arr,
function (array $record) {
if (isset($record['record_type'])) {
return $record['record_type'] != "NS";
} return null;
}
);
working demo
EDIT
If you want to filter for only those records that are of a certain type, e.g. type 'record', following should help:
<?php
$result = array_filter(
$arr,
function (array $record) {
if ($record['type'] == 'record') {
return true;
} return false;
}
);
working demo
If your Goal is to filter array to remove any inner-array that hasn't a record_type, So use array_filter with a callback function fn to check that record_type exist with isset function.
array_filter($arr, fn($el)=>isset($el["record_type"]));
I have a table from which i am fetching some columns
$records=Table::select('id','text','type')->paginate(250)->toArray();
$data=$records->['data'];
I am getting output as :-
array:250 [
0 => array:4 [
"id" => 1
"text" => "text1"
"type" => "A"
]
1 => array:4 [
"id" => 1
"text" => "text2"
"type" => "B"
]
2 => array:4 [
"id" => 1
"text" => "text3"
"type" => "C"
]
3 => array:4 [
"id" => 2
"text" => "text4"
"type" => "A"
]
4 => array:4 [
"id" => 2
"text" => "text5"
"type" => "B"
]
5 => array:4 [
"id" => 2
"text" => "text6"
"type" => "C"
]
6 => array:4 [
"id" => 3
"text" => "text7"
"type" => "A"
]
7 => array:4 [
"id" => 3
"text" => "text8"
"type" => "B"
]
8 => array:4 [
"id" => 3
"text" => "text9"
"type" => "C"
]....
]
I want to convert it into array of objects/array of arrays where results of same id should merge in such a way that value of "type" should be key and value of "text" as value. Below is a sample of expected result:-
array:20 [
{
"id" => 1
"A" => "text1"
"B"=>"text2"
"C"=>"text3"
}
{
"id" => 2
"A" => "text4"
"B"=>"text5"
"C"=>"text6"
}
{
"id" => 3
"A" => "text7"
"B"=>"text8"
"C"=>"text9"
}...
]
I have tried using array_column.
$sortedRecords = array_column($data, 'text','type');
Using array_column, i am able to convert value of "type" as key and "text" value as its value. But i am not able getting how to display id also and how to loop for each distinct id as it is displaying result of only last id.
Following logic might help you on your way. The source array is called $arr, the result array $newArr.
The snippet runs through all unique id's in the source array and accumulates the accompanying text values.
$newArr = [];
$ids = array_values(array_unique(array_column($arr, 'id')));
foreach ($ids as $key => $id) {
foreach ($arr as $value) {
if ($value['id'] === $id) {
$newArr[$key]['id'] = $id;
$newArr[$key][$value['type']] = $value['text'];
}
}
}
working demo
You can get information in groups with group By and perform any operation you need
$records = Table::select('id','text','type')->groupBy('type')->paginate(20)->toArray();
I am beginner php developer.
I have small problem with my array. I use in my project Laravel 7
I have this code:
$items = collect($discount->products->toArray());
It's result me:
Illuminate\Support\Collection {#1783 ▼
#items: array:2 [▼
0 => array:17 [▼
"id" => 1
"product_category_id" => 5
"image_id" => null
"vat_type_id" => 1
"name" => "Produkt 1"
"slug" => "produkt-1"
"lead" => "<p>fewferfer</p>"
"description" => "<p> </p>"
"price" => "123.00"
"loyalty_program_points_price" => 2
"min_student_level" => null
"marked_as_available_at" => "2020-09-30T11:45:51.000000Z"
"deactivated_at" => null
"created_at" => "2020-09-30T11:45:23.000000Z"
"updated_at" => "2020-09-30T11:45:51.000000Z"
"deleted_at" => null
"pivot" => array:3 [▶]
]
1 => array:17 [▼
"id" => 2
"product_category_id" => 5
"image_id" => null
"vat_type_id" => 1
"name" => "Produkt 2"
"slug" => "produkt-2"
"lead" => "<p> </p>"
"description" => "<p>fergfer</p>"
"price" => "21.00"
"loyalty_program_points_price" => 3
"min_student_level" => null
"marked_as_available_at" => "2020-09-30T11:45:38.000000Z"
"deactivated_at" => null
"created_at" => "2020-09-30T11:45:38.000000Z"
"updated_at" => "2020-09-30T11:45:38.000000Z"
"deleted_at" => null
"pivot" => array:3 [▶]
]
]
}
I need convert it to this result:
Array{
1 => 1 (id)
2 => (id)
}
How can I make it?
I need array with only id values
Collections have the pluck method, which allows you to grab all the values of a specific key. To get all of the ids, you'd just need to do
$ids = $items->pluck('id')->all();
If you want them to have the same key as the id as well, pass that as the second parameter
$ids = $items->pluck('id', 'id')->all();
As a note, if products is a relation, then it's already a collection. You do not need to convert it to an array, then back to a collection:
$product_ids = $discount->products->pluck('id')->all();
I have the following code:
public function canceledReasons()
{
$searchs = Zendesk::search()->find('type:ticket tags:cancel');
$searchs = json_decode(json_encode($searchs),true);
foreach ($searchs as $search) {
dump($search);
}
}
It returns an array that has some nested arrays in them I'm trying to display the second array in "tags" if it exists. There might be more than one array in there so it might be good to display them all.
Results
array:100 [▼
0 => array:36 [▼
"url" => "https://example/api/v2/tickets/example.json"
"id" => example
"external_id" => null
"via" => array:2 [ …2]
"created_at" => "2019-08-28T02:05:22Z"
"updated_at" => "2019-08-29T23:00:54Z"
"type" => null
"subject" => "example"
"raw_subject" => "example"
"description" => """
From: example\n
Phone: \n
Location: example\n
URL: https://example.zendesk.com/hc/en-us/categories/#####-Account-Billing\n
Department: \n
\n
Hi,\n
please cancel ▶
\n
Best,\n
Vinay\n
\n
----\n
Zopim\n
https://www.example.com
"""
"priority" => null
"status" => "open"
"recipient" => "example"
"requester_id" => example
"submitter_id" => example
"assignee_id" => example
"organization_id" => null
"group_id" => example
"collaborator_ids" => []
"follower_ids" => []
"email_cc_ids" => []
"forum_topic_id" => null
"problem_id" => null
"has_incidents" => false
"is_public" => true
"due_at" => null
"tags" => array:2 [ …2]
"custom_fields" => array:2 [ …2]
"satisfaction_rating" => null
"sharing_agreement_ids" => []
"fields" => array:2 [ …2]
"followup_ids" => []
"brand_id" => example
"allow_channelback" => false
"allow_attachments" => true
"result_type" => "ticket"
]
1 => array:36 [▶]
2 => array:36 [▶]
3 => array:36 [▶]
4 => array:36 [▶]
When I try
dump($search['tags']);
It returns Undefined index: tags
Just trying to get the results of the 'tags' arrays.
Thanks for the help.
try this...
public function canceledReasons()
{
$searchs = Zendesk::search()->find('type:ticket tags:cancel');
$searchs = json_decode(json_encode($searchs),true);
foreach ($searchs as $search) {
dump($search[0]['tags']);
//or to get all tags array value
foreach ($search[0]['tags'] as $tag) {
dump($tag);
}
}
}
```
Question background
Hello, I have the following array of movie crew members:
array:7 [▼
0 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5e9d"
"department" => "Directing"
"id" => 139098
"job" => "Director"
"name" => "Derek Cianfrance"
"profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
]
1 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5ed7"
"department" => "Writing"
"id" => 139098
"job" => "Story"
"name" => "Derek Cianfrance"
"profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
]
2 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5edd"
"department" => "Writing"
"id" => 132973
"job" => "Story"
"name" => "Ben Coccio"
"profile_path" => null
]
3 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5ee3"
"department" => "Writing"
"id" => 139098
"job" => "Screenplay"
"name" => "Derek Cianfrance"
"profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
]
4 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5ee9"
"department" => "Writing"
"id" => 132973
"job" => "Screenplay"
"name" => "Ben Coccio"
"profile_path" => null
]
5 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5eef"
"department" => "Writing"
"id" => 1076793
"job" => "Screenplay"
"name" => "Darius Marder"
"profile_path" => null
]
11 => array:6 [▼
"credit_id" => "52fe49de9251416c750d5f13"
"department" => "Camera"
"id" => 54926
"job" => "Director of Photography"
"name" => "Sean Bobbitt"
"profile_path" => null
]
]
As you can see this is a list of credits I'm getting via the TMDb API. The first step of building the above array was to filter out all jobs that I don't want to display, here's how I did that:
$jobs = [ 'Director', 'Director of Photography', 'Cinematography', 'Cinematographer', 'Story', 'Short Story', 'Screenplay', 'Writer' ];
$crew = array_filter($tmdbApi, function ($crew) use ($jobs) {
return array_intersect($jobs, $crew);
});
My question
I'd like to figure out how to take the above result one step further and combine jobs where the id is the same, so as to end up with something like this, for example:
array:7 [▼
0 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5e9d"
"department" => "Directing"
"id" => 139098
"job" => "Director, Story, Screenplay"
"name" => "Derek Cianfrance"
"profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
]
I have also considered ditching doing this in my logic and instead doing it in my blade template, but I'm not sure how to achieve that.
How would you accomplish this?
You could nicely use Laravel's Collection in such a situation, which has a great number of methods which will help you in this case.
First, turn this array (the one you already filtered on jobs) to a Collection:
$collection = collect($crew);
Second, group this Collection by it's ids:
$collectionById = $collection->groupBy('id');
Now, the results are grouped by the id and transformed to a Collection in which the keys correspond to the id, and the value an array of 'matching' results. More info about it here.
Finally, just a easy script that iterates through all the results for each id and combines the job field:
$combinedJobCollection = $collectionById->map(function($item) {
// get the default object, in which all fields match
// all the other fields with same ID, except for 'job'
$transformedItem = $item->first();
// set the 'job' field according all the (unique) job
// values of this item, and implode with ', '
$transformedItem['job'] = $item->unique('job')->implode('job', ', ');
/* or, keep the jobs as an array, so blade can figure out how to output these
$transformedItem['job'] = $item->unique('job')->pluck('job');
*/
return $transformedItem;
})->values();
// values() makes sure keys are reordered (as groupBy sets the id
// as the key)
At this point, this Collection is returned:
Collection {#151 ▼
#items: array:4 [▼
0 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5e9d"
"department" => "Directing"
"id" => 139098
"job" => "Director, Story, Screenplay"
"name" => "Derek Cianfrance"
"profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
]
1 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5edd"
"department" => "Writing"
"id" => 132973
"job" => "Story, Screenplay"
"name" => "Ben Coccio"
"profile_path" => null
]
2 => array:6 [▼
"credit_id" => "52fe49dd9251416c750d5eef"
"department" => "Writing"
"id" => 1076793
"job" => "Screenplay"
"name" => "Darius Marder"
"profile_path" => null
]
3 => array:6 [▼
"credit_id" => "52fe49de9251416c750d5f13"
"department" => "Camera"
"id" => 54926
"job" => "Director of Photography"
"name" => "Sean Bobbitt"
"profile_path" => null
]
]
}
Note: to use this Collection as an array, use:
$crew = $combinedJobCollection->toArray();
There are multiple ways to achieve this, for example: search the array for overlapping id's, but I think this is the easiest way to achieve this.
Goodluck!
Since you are trying to edit the array elements and its size, I believe array_map() or array_filter() won't be a solution to this.
This is what I could come up with...
$jobs = [
'Director', 'Director of Photography', 'Cinematography',
'Cinematographer', 'Story', 'Short Story', 'Screenplay', 'Writer'
];
$crew = [];
foreach($tmdbApi as $key => $member) {
if($member['id'] == $id && in_array($member['job'], $jobs)) {
if(!isset($crew[$key])) {
$crew[$key] = $member;
} else {
$crew_jobs = explode(', ', $crew[$key]['job']);
if(!in_array($member['job'], $crew_jobs)) {
$crew_jobs[] = $member['job'];
}
$crew[$key]['job'] = implode(', ', $crew_jobs);
}
}
}
Hope this answers your question :)