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();
Related
I want to get from my answer only the values of the key_number; even though I return the foreach inside another foreach, it returns only one index and not the two values of the request.
Controller
foreach (array($request['key_number']) as $notaFiscal) {
foreach($notaFiscal as $notas) {
dd($notas);
}
// $moviment->document()->create($notasFiscais);
}
Request
dd($request);
+request: Symfony\Component\HttpFoundation\InputBag {#1535
#parameters: array:8 [
"type" => null
"people_id" => 5
"company_id" => 1
"vehicle_id" => 2
"department_id" => "12179"
"document_id" => null
"document_type_id" => 1
"key_number" => array:2 [
0 => array:2 [
"title" => "New Title"
"key_number" => "444444"
]
1 => array:2 [
"title" => "New Title"
"key_number" => "555555"
]
]
]
}
Request foreach index key_number
array:2 [ // app\Http\Controllers\MovimentController.php:50
0 => array:2 [
"title" => "New Title"
"key_number" => "444444"
]
1 => array:2 [
"title" => "New Title"
"key_number" => "555555"
]
]
foreach inside foreach return only one index
array:2 [ // app\Http\Controllers\MovimentController.php:51
"title" => "New Title"
"key_number" => "444444"
]
Return all index key_number, not one index.
So there are tons of questions like this, but I haven't found an answer the suits my desired outcome.
consider the following array:
array:13 [
"Peripheral Neuropathy" => array:3 [
"name" => "peripheral_neuropathy"
"value" => array:1 [
0 => "yes"
]
"dependencies" => array:5 [
"neuropathy_staging_fap" => array:1 [
0 => "2"
]
"neuropathy_staging_pnd" => array:1 [
0 => "II"
]
"specify_type" => array:1 [
0 => "Sensory"
]
"autonomic" => array:1 [
0 => "yes"
]
"sensory_fiber_size" => array:1 [
0 => "Small"
]
]
]
"Neuropathic pain" => array:3 [
"name" => "neuropathic_pain"
"value" => array:1 [
0 => "yes"
]
"dependencies" => []
]
"Functional Motor Assessment" => array:3 [
"name" => "functional_motor_assessment"
"value" => array:1 [
0 => "Yes"
]
"dependencies" => array:3 [
"functional_motor_assessment_test_name" => "sample"
"functional_motor_assessment_test_score" => "10"
"functional_motor_assessment_date" => "2020-02-11"
]
]
"Assessment name" => array:3 [
"name" => "functional_motor_assessment_test_name"
"value" => "sample"
"dependencies" => []
]
"Assessment Score" => array:3 [
"name" => "functional_motor_assessment_test_score"
"value" => "10"
"dependencies" => []
]
"Assessment Date" => array:3 [
"name" => "functional_motor_assessment_date"
"value" => "2020-02-11"
"dependencies" => []
]
"Carpal Tunnel Syndrome" => array:3 [
"name" => "carpal_tunnel_syndrome"
"value" => array:1 [
0 => "yes"
]
"dependencies" => []
]
"EMG" => array:3 [
"name" => "emg"
"value" => array:1 [
0 => "yes"
]
"dependencies" => array:5 [
"emg_type" => array:1 [
0 => "Median"
]
"median_amplitude" => "10"
"median_CV" => "10"
"median_tml" => "10"
"median_size" => array:1 [
0 => "7cm"
]
]
]
"EMG Type" => array:3 [
"name" => "emg_type"
"value" => array:1 [
0 => "Median"
]
"dependencies" => array:4 [
"median_amplitude" => "10"
"median_CV" => "10"
"median_tml" => "10"
"median_size" => array:1 [
0 => "7cm"
]
]
]
"Amplitude" => array:3 [
"name" => "median_amplitude"
"value" => "10"
"dependencies" => []
]
"CV" => array:3 [
"name" => "median_CV"
"value" => "10"
"dependencies" => []
]
"TML" => array:3 [
"name" => "median_tml"
"value" => "10"
"dependencies" => []
]
"Size" => array:3 [
"name" => "median_size"
"value" => array:1 [
0 => "7cm"
]
"dependencies" => []
]
]
As we can see there are duplicates, for example look at: Functional Motor Assessment under dependencies - this is correct, but directly under Functional Motor Assessment is Assessment name with the name functional_motor_assessment_test_name.
This is the duplicate. This specific array, Assessment name should not exist because the name already exists in Functional Motor Assessment's dependencies array.
So I thought, I will write the following function:
protected function alreadyExists(array $values, string $fieldName) {
if (empty($values)) {
return false;
}
foreach ($values as $key => $value) {
foreach ($value as $k => $v) {
if ($k === 'dependencies' && !empty($value[$k])) {
return array_key_exists($fieldName, $value[$k]);
}
}
}
return false;
}
where $value is the above array and in this case $fieldName would be (for example) functional_motor_assessment_test_name.
The idea here is that this should walk through the array looking for any key that matches: functional_motor_assessment_test_name and return true if found or false if not (false if the (above) array is empty).
Theres a couple rules:
Return false if the value array is empty, because obviously it wont exist.
Return false if never found
Skip the check if the the dependencies array is empty (it can be empty sometimes).
This is where it should move on to the next array, so if not found in Peripheral Neuropathy move on to Neuropathic pain and so on ...
I think this function has to be recursive, but I am not sure where to put the recursive aspect, to say: well I didn't find it in Peripheral Neuropathy, let's check Neuropathic pain and so on and so forth. Until it is either found or not.
I tried array_walk_recursive, but as I expected while reading the docs, there is no way to break from that kind of function - so I thought, this function I have is on the right track, I just need to make it recursive.
Ideas?
There's no need to loop over the second level arrays, just get the dependencies element directly with indexing.
public function alreadyFound(array $values, string $fieldName) {
foreach ($values as $item) {
if (!empty($item['dependencies']) && array_key_exists($fieldName, $item['dependencies'])) {
return true;
}
return false;
}
If there can be dependencies nested within dependencies, you do need a recursive solution.
protected function alreadyExists(array $values, string $fieldName) {
if (array_key_exists($fieldName, $values)) {
return true;
}
foreach ($values as $item) {
if (!empty($item['dependencies']) && $this->alreadyExists($item['dependencies'], $fieldName) {
return true;
}
}
return false;
}
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,
Am working on a Laravel application whereby I have an associative array that am to pass to an API endpoint, Before posting to the API, I want to delete the img key together with its value . I have tried to use unset function but it is not removing the img key
Array where I want to remove the image property
$a[] = [
0 => array:4 [
"name" => "Martoo nnn"
"relationship" => "Spouse"
"dob" => "2001-02-03"
"img" => "img.png"
]
1 => array:4 [
"name" => "sdsdsd sdsdsd"
"relationship" => "Child"
"dob" => "2019-04-04"
"img" => "img1.png"
]
2 => array:4 [
"name" => "sdsdsd sddds"
"relationship" => "Child"
"dob" => "2019-04-05"
"img" => "img2.png"
]
3 => array:4 [
"name" => "dssdsd dsdsd"
"relationship" => "Child"
"dob" => "2019-04-02"
"img" => "img3.png"
]
4 => array:4 [
"name" => "dssdsd dssdsd"
"relationship" => "Child"
"dob" => "2019-04-04"
"img" => "img4.png"
]
];
Unset method
$array = $a;
unset($array['img']);
//dd($a);
You can do something like this,
foreach ($array as $key => &$value) { // & defines changes will be made # value itself
unset($value['img']);
}
And Yes, I don't understand why you initialised $a as $a[]?
$newarray = array_filter($a, function($k) {
return $k != 'img';
}, ARRAY_FILTER_USE_KEY);
and pass this new array
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 :)