I have he next array looks like:
array:50 [▼
0 => array:39 [▶]
1 => array:39 [▶]
2 => array:39 [▶]
]
So I want to get arrays with a value in common, for example:
array:39 [▼
"id" => 121
"user" => 368
]
array:39 [▼
"id" => 121
"user" => 3687
]
array:39 [▼
"id" => 500
"user" => 452
]
I want to get the two arrays with the attribute
id 121, I was trying to looping the array with foreach looks like:
foreach ($info as $val){
foreach($info as $f ){
if($f["id"]==$val["id"]){
//get the multiple arrays
}
}
}
So, I can't get all the arrays, some idea to how can do that?
I'd use a Collection.
collect your array of arrays:
$collection = collect([
[
"id" => 121
"user" => 368
],
[
"id" => 121
"user" => 3687
],
[
"id" => 500
"user" => 452
]
]);
Use the where method to filter based on a specific key's value:
$filtered = $collection->where('id', 121);
$filtered->all();
/*
[
['id' => '121', 'user' => 368],
['id' => '121', 'user' => 3687],
]
*/
Other where-like methods are available. Be sure to read through all of the documentation on Collections, it's full of great examples!
If you're now convinced that you should use Collections for everything, check out Adam Wathan's awesome book (and other resources): Refactoring to Collections (not free)
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'm trying to increment during the map method, however my variable doesn't seem to save the new value. My code:
$position = 0;
$statement = $medias->map(fn(string $media) => [
'position' => ++$position
])->values();
My expected result would be:
#items: array:4 [
0 => array:4 [
"position" => 1
]
1 => array:4 [
"position" => 2
]
2 => array:4 [
"position" => 3
]
3 => array:4 [
"position" => 4
]
]
However it's actually
#items: array:4 [
0 => array:4 [
"position" => 1
]
1 => array:4 [
"position" => 1
]
2 => array:4 [
"position" => 1
]
3 => array:4 [
"position" => 1
]
]
Is incrementing inside map not possible or am I doing something wrong here?
The problem here is that you expect $position variable to be passed by reference, which is not the case.
Arrow functions use by-value variable binding. This is roughly equivalent to performing a use($x) for every variable $x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope. Anonymous functions can be used instead for by-ref bindings. PHP Manual - Arrow Functions
A workaround for you could be like this:
// Either
$posObj = new \stdClass();
$posObj->position = 0;
// or
$posObj = (object)array('position' => 0);
$statement = $medias->map(fn(string $media) => [
'position' => ++$posObj->position
])->values();
Hi First i am getting dat from database as an array then I want to convert my array data into object I tried many function but not work in laravel api .I want to convert array data into object and return as JSON for API i google it several time but did not find any solutions any body help thanks in advance.
for api i am using this
return response()->json(['data' => $categories, 'status_code' => 200, 'status' => true],200);
i have tried
cateogry is an array $categories
$data_object = (object)$categories;
$data_array = (array)$categories;
dd($data_array);
dd($data_object);
both return same result
this is the result
array:14 [
37 => array:5 [
"id" => 37
"name" => "Red abya"
"alias" => "red-abya"
"is_featured" => 0
]
38 => array:5 [
"id" => 38
"name" => "Black Dress"
"alias" => "black-dress"
"is_featured" => 0
]"is_featured" => 0
]
1 => array:6 [
"id" => 1
"name" => "Abayas"
"alias" => "abayas"
"is_featured" => 1
"sub_categories" => array:2 [
0 => array:5 [
"id" => 37
"name" => "Red abya"
"alias" => "red-abya"
"is_featured" => 0
]
1 => array:5 [
"id" => 36
"name" => "White abaya"
"alias" => "white-abaya"
"is_featured" => 0
]
]
]
25 => array:5 [
"id" => 25
"name" => "Discount"
"alias" => "discount"
"is_featured" => 0
]
]
If you want JSON at the end you can try changing this:
$data_object = (object)$categories;
to
$data_object = (object)$categories;
$data_object->toJson();
dd($data_object);
I will assume $categories is a collection array. Then in your view you can json_encode($data_object) it.
Try this
$categories = array_map(function($categories){
return (object)$categories;
}, $categories);
if you use postman you send and receive data in json format. so for this you can use json_encode() to convert data to json format and json_decode() to convert data to array() format. also in laravel you get data by Request instans and send response by response() helper, so if you need get data in array format you can use this:
$data_array = (array)$request->all()
and for send data use:
response()->json($data_array , 200);
if you want stdclass use (object) instead array
I want to have an array with the info about each registration type associated with a registration. For example if for the registration with id "1" the user selected two registration types of type "General" and one of the type "Plus" the $regTypes array should have this content with 2 item:
'registrationTypes' => [
[
'name' => 'general',
'price' => '5',
'quantity' => '2'
],
[
'name' => 'plus',
'price' => '10',
'quantity' => '1'
]
]
The registration_types table have the name and the price. So I have this query to get some info about a registration in a conference.
$registration = Registration
::with('conference', 'Conference.registrationTypes')->where('id', 1)->first();
And then I have this code to create the array with the necessary info:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$regTypes [
'regType' => [
'name' => $registration->conference->registrationTypes[$key]['name'],
'price' => $registration->conference->registrationTypes[$key]['price']
]
];
}
My doubt is how to also store the quantity in the $regTypes array. Because the quantity is not stored in the database.
Maybe to get the quantity is necessary to do antoher query. With this code below:
$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);
//dd($registrationTypeDetails);
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
dump($type_counts);
The $type_counts shows the quantity of each registration type associated with the registration:
array:2 [▼
"general" => 2
"plus" => 1
]
Do you know how to use this $type_counts content to store the quantity properly in the $regTypes array?
To directly answer your question (IE not change the controller code, just "use this $type_counts content to store the quantity properly in the $regTypes array"), I'm hopeful this should work for you:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$typeName = $registration->conference->registrationTypes[$key]['name'];
$regTypes [
'regType' => [
'name' => $typeName,
'price' => $registration->conference->registrationTypes[$key]['price'],
'quantity' => $type_counts[$typeName]
]
];
}
Basically just pulling the count from the $type_counts array based on the name of the Registration Type being the key that you added in the foreach ($registrationTypeDetails->participants as $p) loop.
Depending upon what you are after, it might be easier just to loop on the registration types, rather than go through $registration->conference->registrationTypes. This way you don't have duplicates. But that assumes you don't want duplicates :)
I hope this code useful for you .If you need the number of participants in any type, you can use the following code:
$registration = Registration::with('conference','Conference.registrationTypes','Conference.registrationTypes.participants')
->where('id',$regID)->first();
$result=$registration->conference->registrationTypes->each(function ($item, $key) use($registration) {
$item['try_count']=$item->participants->count();
});
dd($result->toArray());
I added the try_count variable to the final result:
array:2 [▼
0 => array:6 [▼
"id" => 1
"name" => "general"
"price" => 0
"conference_id" => 1
"try_count" => 8
"participants" => array:8 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
5 => array:5 [▶]
6 => array:5 [▶]
7 => array:5 [▶]
]
]
1 => array:6 [▼
"id" => 2
"name" => "plus"
"price" => 1
"conference_id" => 1
"try_count" => 5
"participants" => array:5 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
]
]
]
It sounded crazy simple to me at first but I can't find the solution!
Here is My collection :
Collection {#433
#items: array:432 [
0 => array:5 [
"word_id" => 12218
"name" => "ordered"
"rank" => 12217
"is_real" => 1
"id" => 1
]
1 => array:5 [
"word_id" => 12097
"name" => "one-dimensional"
"rank" => 12096
"is_real" => 1
"id" => 2
]
2 => array:5 [
"word_id" => 19679
"name" => "watery"
"rank" => 19678
"is_real" => 1
"id" => 3
]
.
.
.
But I want it to be like this :
Collection {#433
#items: array:432 [
0 => array:5 [
"name" => "ordered"
"id" => 1
]
1 => array:5 [
"name" => "one-dimensional"
"id" => 2
]
2 => array:5 [
"name" => "watery"
"id" => 3
]
.
.
.
How can it be done with laravel collection? Do I have to change my collection to array and do the manipulation myself? How?
Or you can also use
$collection = $collection ->map(function ($item) {
return collect($item)->forget(['work_id','rank','is_real']);
});
$collection = $collection->map(function ($item) {
return array_only($item, ['id', 'name']);
});
You can use the only() method.
The only method returns the items in the collection with the specified
keys
$collection = $collection->map(function ($item) {
return $item->only(['id', 'name'])
});
This way your collection still remains as collections;
Please note, only() method is only available for Laravel collections
not for an array
An alternative approach could be to use the Arr::only() helper to reduce the items:
$collection = $collection->map(static fn($item) => Arr::only($item, ['id', 'name']));