I am using foreach loop that outputs an array
$dinnerDetails = array();
$lastDinnerDate = '';
$newDate = '';
foreach ($invitations as $invitation) {
$lastDinnerDate = $invitation['dinner_date'];
if ($invitation['dinner_date'] > $lastDinnerDate) {
$newDate = 'yes';
} else {
$newDate = 'no';
}
$dinnerDetails[] = array(
'request_id' => $invitation['request_id'],
'dinner_date' => $invitation['dinner_date'],
'dinner_id' => $invitation['dinner_id'],
'new_dinner' => $newDate
);
}
Output looks like this
array:4 [▼
0 => array:3 [▼
"request_id" => "48"
"dinner_id" => "36"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "yes"
]
1 => array:3 [▼
"request_id" => "51"
"dinner_id" => "40"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "no"
]
2 => array:3 [▼
"request_id" => "50"
"dinner_id" => "36"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "yes"
]
3 => array:3 [▼
"request_id" => "52"
"dinner_id" => "41"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "no"
]
]
My question is how can i count the number of times the dinner_id appeared. I would like to pass that value as part of the array because $dinnerDetails is being passed to the view so it will make it easier to display the count. The view already displays the data via foreach loop its only the count i need for each dinner_id
I assume you want to count the ID's and not the label / name itself, one ever so simple way would be doing it like so, simply place this inside of your foreach loop
$countDinner[$invitation['dinner_id']] = isset($countDinner[$invitation['dinner_id']]) ? $countDinner[$invitation['dinner_id']] + 1 : 1;
One coud also use a if clause instead of a ternary operator if one preffers, don't forget to place a
$countDinner = array();
Before the foreach loop to initialize the array, you should now have a array with the count of each dinner_id.
To add it to the existing array simply loop through as following:
foreach($dinnerDetails as &$dinnerDetail){
$dinnerDetail['count'] = $countDinner[$dinnerDetail['dinner_id']];
}
and the end result will look like this
0 => array:3 [▼
"request_id" => "48"
"dinner_id" => "36"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "yes"
"count" => 2
]
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"]));
My project has an array made of a request with an array of inputs inside, as it follows:
array:8 [▼
"type_id" => array:1 [▼
0 => "1"
]
"zip_code" => array:1 [▼
0 => "88801500"
]
"street_address" => array:1 [▼
0 => "Avenida Getúlio Vargas"
]
"number" => array:1 [▼
0 => "asdasd"
]
"street_address_2" => array:1 [▼
0 => "asdasd"
]
"city_id" => array:1 [▼
0 => "4384"
]
"neighborhood" => array:1 [▼
0 => "Centro"
]
"created_by" => 2
]
But when I try to run said array on a foreach to insert it on the database, I get a result that doesnt make sense:
array:1 [▼
0 => "1"
]
My code:
dd($dataEnderecos); //This is for debug purposes, it shows the initial array on this question.
foreach ($dataEnderecos as $enderecos) {
dd($enderecos); //This is for debug purposes, it shows the secondary array on this question.
$enderecoID = $this->address->create($enderecos)->id;
$this->repository->enderecos()->attach($enderecoID);
}
I managed to fix this by using a for loop and using another variable to receive the results of the initial array:
for ($i = 0; $i < $limit; $i++) {
$insert = array(
'type_id' => $dataEnderecos['type_id'][$i],
// ^^^^ ^^^^ ^^^^
// Initial Array Secondary Array Index
);
}
i have form to make a bill for multiple products,
that form return request like this
#parameters: array:5 [▼
"quantity" => array:2 [▼
0 => "1"
1 => "2"
]
"product" => array:2 [▼
0 => "Mr. Jasen Beer,OliveDrab,XS"
1 => "Carlotta Yundt"
]
"date" => array:2 [▼
0 => "2019-12-29"
1 => "2019-12-29"
]
"id" => array:2 [▼
0 => "15"
1 => "11"
]
]
}
i need to loop all arrays to make insert all at once
thanks.
Try to loop it like this, you will get the array wrap every product's attributes:
$inserted_array = [];
foreach($parameters as $key => $values) {
foreach($values as $index => $val) {
$inserted_array[$index][$key] = $val;
}
}
\DB::table('table_name')->insert($inserted_array);
And I found that there is id in your array, remember to make it fillable.
I'm trying to store values in an array structured like this:
{"parent":
{"class":"Green","user_name":"Nitish","user_loc":"Delhi","user_id":1,"user_blockclass":null,
"child":[
{"class":"Green","user_name":null,"user_loc":null,"user_id":1,"user_blockclass":"fst",
"child":[
{"class":"Green","user_name":"pandey","user_loc":"sdgfsjd","user_id":6,"user_blockclass":"fst"},
{"class":"Green","user_name":"chaku","user_loc":"sdgjs","user_id":7,"user_blockclass":"snd"},
{"class":"Green","user_name":"iks","user_loc":"sjkdfhkjs","user_id":8,"user_blockclass":"trd"},
{"class":"Green","user_name":"yash","user_loc":"hfksjdhfk","user_id":9,"user_blockclass":"frt"},
{"class":"Green","user_name":"joshi","user_loc":"dsfh","user_id":10,"user_blockclass":"fth"}
]},
{"class":"Green","user_name":null,"user_loc":null,"user_id":1,"user_blockclass":"snd",
"child":[
{"class":"Green","user_name":"pandey","user_loc":"sdgfsjd","user_id":6,"user_blockclass":"fst"},
{"class":"Green","user_name":"chaku","user_loc":"sdgjs","user_id":7,"user_blockclass":"snd"},
{"class":"Green","user_name":"iks","user_loc":"sjkdfhkjs","user_id":8,"user_blockclass":"trd"},
{"class":"Green","user_name":"yash","user_loc":"hfksjdhfk","user_id":9,"user_blockclass":"frt"},
{"class":"Green","user_name":"joshi","user_loc":"dsfh","user_id":10,"user_blockclass":"fth"}
]},
]
}
}
I'm trying to place this in two different array and the joining them, but it is not getting the approrpiate result, I've used a variable which iterates to store the different values, if I don't use iteration it overlaps the values and only shows the last stored values. Following is my code:
$blockclass = ['fst', 'snd', 'trd', 'frt', 'fth'];
$i = 0;
$children = $user->relations()->wherePlanId($selectplan)->get();
foreach($children as $ch)
{
$j = 0;
$subuserinfo = [];
$parent_id = $ch->pivot->child;
$subuser = User::find($ch->pivot->child);
$subuserinfo['class'] = "Green";
$subuserinfo['user_name'] = $ch->name;
$subuserinfo['user_loc'] = $ch->city;
$subuserinfo['user_id'] = $ch->id;
$subuserinfo['user_blockclass'] = $blockclass[$i];
if($subuser){
$subchildren = $subuser->relations()->wherePlanId($selectplan)->get();
foreach($subchildren as $subchild)
{
$subsubuser = User::find($subchild->pivot->child);
$subsubuserinfo['class'] = "Green";
$subsubuserinfo['user_name'] = $subsubuser->name;
$subsubuserinfo['user_loc'] = $subsubuser->city;
$subsubuserinfo['user_id'] = $subsubuser->id;
$subsubuserinfo['user_blockclass'] = $blockclass[$j];
$subuserinfo['child'][$i][$j++] = $subsubuserinfo;
}
}
else
{
$subuserinfo['child'][$i][$j++] = NULL;
}
$userinfo['child'][$i++] = $subuserinfo;
}
$tree = $userinfo;
dd($tree);
Currently the data structure which I'm getting is in following format:
array:6 [▼
"class" => "Green"
"user_name" => "Nitish"
"user_loc" => "Delhi"
"user_id" => 1
"user_blockclass" => null
"child" => array:4 [▼
0 => array:6 [▼
"class" => "Green"
"user_name" => null
"user_loc" => null
"user_id" => 1
"user_blockclass" => "fst"
"child" => array:1 [▼
0 => array:5 [▼
0 => array:5 [▼
"class" => "Green"
"user_name" => "pandey"
"user_loc" => "sdgfsjd"
"user_id" => 6
"user_blockclass" => "fst"
]
1 => array:5 [▼
"class" => "Green"
"user_name" => "chaku"
"user_loc" => "sdgjs"
"user_id" => 7
"user_blockclass" => "snd"
]
2 => array:5 [▼
"class" => "Green"
"user_name" => "iks"
"user_loc" => "sjkdfhkjs"
"user_id" => 8
"user_blockclass" => "trd"
]
]
]
]
1 => array:6 [▶]
2 => array:6 [▶]
3 => array:6 [▶]
I'm not able to fetch the data in this format, also after this I want to place the data to be used as json format. Help me out.
I thinkyou should replace all $subuserinfo['child'][$i][$j++] = $subsubuserinfo; with $subuserinfo['child'][$j++] = $subsubuserinfo;
I see you are using Laravel? If you use return response()->json($tree); it will print JSON.
If you also want the parent in front of the JSON you can use this:
return response()->json(['parent' => $tree]);
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 :)