I have 2 arrays of data and i need to join the results of this two arrays.
I can use array_combine but there is 2 issues:
my first array is coming from check boxes and send data of checked check-box only
my second array coming from input fields and sending all my inputs
the issue here is my first array have (for example) 3 values while my second array has 7 values
This kind of combine will return the error of:
array_combine(): Both parameters should have an equal number of elements
Data
this is my dd results:
"optionID" => array:3 [▼ //check-box values
0 => "1"
1 => "2"
2 => "11"
]
"optionPRICE" => array:8 [▼ //input values
0 => "98"
1 => null
2 => null
3 => null
4 => null
5 => null
6 => null
7 => null
]
what I want
what i'm looking for is to get values of my inputs from checked check-boxes and not the rest of them.
example i check data 1,2,3 i get value 1,2,3 whether is null of filled and not getting 4,5,6,7 as you see in my dd data above.
code
this is what my html looks like
<tr>
<td class="text-center" width="50">
<label class="switch switch-small">
<input type="checkbox" name="optionID[]" value="11"> //checkbox arrays
<span></span>
</label>
</td>
<td>
CDN
</td>
<td class="text-center">
//input arrays
<input class="form-control" type="number" name="optionPRICE[]">
</td>
</tr>
I'm looking to get my data in any of this 2 kinds
this
"optionID" => array:3 [▼ //check-box values
0 => "1"
1 => "2"
2 => "11"
]
"optionPRICE" => array:8 [▼ //input values
0 => "98"
1 => null
2 => null
]
or this
"optionID" => array:3 [▼
"array" => array:2 [
0 => "1",
1 => "98",
],
"array" => array:2 [
0 => "2",
1 => null,
],
"array" => array:2[
0 => "11",
1 => null,
],
]
any idea?
Update
Based on answers if i use mapping function to return data as my second sample desire it would be confusing to naming data and relate them to my model column, so I share my model names and explain which data has to go in which column in order to be save in right place.
Schema
Schema::create('product_options', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->nullable()->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->integer('option_id')->nullable()->unsigned();
$table->foreign('option_id')->references('id')->on('options')->onDelete('cascade');
$table->string('price')->nullable();
});
optionID data has to go in option_id column and optionPRICE data to price column.
For product_id column as this data will save after my product is saved so i just simply get the id by $product->id that column is out of issue.
Update 2
I tried many different conditions to see how data will send here is a serious issue based on the answers I've got.
When I pass data from 1 selected option, e.g. select colors and fill some data to send it works as it supposed to.
But when I select second option e.g. select sizes for this option only checkbox id's will send and data of optionPRICE will not send, this issue applies for next options as well (option 3,4,5,6....)
Here is a sample:
array:3 [▼
0 => array:3 [▼ //this is from colors (included price)
"option_id" => "4"
"price" => "768"
"product_id" => 50
]
1 => array:3 [▼ //this is also from colors (included price)
"option_id" => "5"
"price" => "5467"
"product_id" => 50
]
2 => array:3 [▼ //this one is from sizes (not included price, while i filled the price!)
"option_id" => "10"
"price" => null
"product_id" => 50
]
]
Update 3
OK, I worked around and tested some ways to fix the issue, here is what i figured and what i achieved:
Th issue of returning my third price null (update 2) was because we were counting prices array and not inputs of checked check-boxes. that was why 3rd option was null while my actual filled option was 11. (refer to my data dd top of my question)
I can get now actual filled optionPRICE fields and not by counting them but with the values.
Here is what I did so far:
$options = $request->input('optionID');
$prices = $request->input('optionPRICE');
$collection = array_filter($prices, function($value) {
return !is_null($value);
});
$toInsert = array_merge([$options, $collection]);
dd($toInsert);
code above returns this:
array:2 [▼
0 => array:3 [▼
0 => "4"
1 => "5"
2 => "10"
]
1 => array:3 [▼
0 => "768"
1 => "5467"
5 => "5465496"
]
]
but if i fill price for only 2 of my check-boxes will be like:
array:2 [▼
0 => array:3 [▼
0 => "4"
1 => "5"
2 => "10"
]
1 => array:2 [▼
0 => "768"
1 => "5467"
]
]
This is good to get only input data without needs of counting array elements just pure values.
After this I need to join this 2 array of mine and return null in case of second case happens (3 check-box, 2 price).
Any help on that?
This should get you your first desired solution using array_slice:
// Get the length of the smaller array
$minLength = min(count($arr1), count($arr2));
$result = [
'optionID' => array_slice($arr1, 0, $minLength),
'optionPRICE' => array_slice($arr2, 0, $minLength),
];
For your second desired solution, you could try something like this (if I understood correctly):
$checkboxes = [1, 2, 11];
$inputs = [98, null, null];
$result = collect($checkboxes)->map(function ($item, $key) use($inputs) {
return [$item, $inputs[$key] ?? null];
})->toArray();
dd($result);
// array:3 [
// 0 => array:2 [
// 0 => 1
// 1 => 98
// ]
// 1 => array:2 [
// 0 => 2
// 1 => null
// ]
// 2 => array:2 [
// 0 => 11
// 1 => null
// ]
// ]
Related
php unset is working but on reload the session data is still there:
I'm building simple addtocart and remove from cart in php/symfony5, but I'm unable to unset the array from multi dimension array in symfony session.
^ array:3 [▼
0 => array:1 [▼
"items" => array:4 [▼
0 => 9
1 => "Dry fruit"
2 => "1234"
3 => "250g"
]
]
1 => array:1 [▼
"items" => array:4 [▼
0 => 8
1 => "Pumpkin"
2 => "123"
3 => "x"
]
]
This is my cart controller:
$basket = $session->get('basket',[]);
dump($basket);
$size = $session->get('size');
if($request->isMethod('POST')){
$id = $request->request->get('0');
foreach($basket as $key => $value){
if($value['items'][0] == $id){
unset($basket[$key]['items']);
dd($basket);
//$session->set('basket',[]);
//return $this->redirectToRoute('cart');
}
}
}
On the above code when I click remove button in twig and when dd($basket) is done the array is empty like below:
^ array:3 [▼
0 => [] //empty
1 => array:1 [▼
"items" => array:4 [▼
0 => 8
1 => "Pumpkin"
2 => "123"
3 => "x"
]
]
But, when I comment dd($basket) and page is reloaded the array is as it is like before(seems reverted idk) and if I uncomment $session->set('basket',[]); everything is empty.
what I want to achieve here is, how to remove array from session multi dimension array?
You simply need to set the session variable to the updated $basket value.
// get a copy of the basket from the session
$basket = $session->get('basket',[]);
// do whatever to update $basket here
// overwrite the basket in the session
$session->set('basket', $basket);
// then return a Response
I have pivot table vacancy_tag. I tried different options (value,select, lists and etc), but didn't go further than that. My request:
Vacancy::where('id',1)->with(['tags' => function ($q){
$q->select('tags.id')->pluck('id');
}])->get()->toArray();
return this:
"id" => 1,
"title" => "pm",
"tags" => array:2 [▼
0 => array:1 [▼
"id" => 1
]
1 => array:1 [▼
"id" => 2
]
but need this:
"id" => 1,
"title" => "pm",
"tags" => [
1,
2
]
I would like to receive the data result in a query, without using a methods transformation of the collection, if possible.
PS: I slightly corrected the example, need to display all fields of the vacancy + an array of tags.
Basically, I am building html form inputs that have dynamic inputs For example In below example if user want to increase the unit_type then user can add the new input from front end and send it to store
Note: If user will add the unit_type then all others keys will automatically added. Like if user try to increase the unit_type then unit_address and all other inputs increase accordingly.
Right Now I have the array like this
array:7 [
"unit_type" => array:2 [
0 => null
1 => null
]
"unit_address" => array:2 [
0 => null
1 => null
]
"unit_phone" => array:2 [
0 => null
1 => null
]
"fax" => array:2 [
0 => null
1 => null
]
"installed_capacity" => array:2 [
0 => null
1 => null
]
"production_capacity" => array:2 [
0 => null
1 => null
]
"unit_email" => array:2 [
0 => null
1 => null
]
]
Expected Result
[
[
//Here all keys contain the first values of all arrays
'unit_type'=>'first_value',
'unit_address'=>'first_value',
'unit_phone'=>'first_value',
'fax'=>'first_value',
'installed_capacity'=>'first_value',
'production_capacity'=>'first_value',
'unit_email'=>'first_value'
],
[
//Here all keys contain the second values of all arrays
'unit_type'=>'second_value',
'unit_address'=>'second_value',
'unit_phone'=>'second_value',
'fax'=>'second_value',
'installed_capacity'=>'second_value',
'production_capacity'=>'second_value',
'unit_email'=>'second_value'
]
]
Loop through the existing return data and build the new array like so:
$input_array = []; //your data received from the front end
$return_array = []; //structured data return
foreach($input_array as $field => $fieldData){
foreach ($fieldData as $key => $data){
$return_array[$key][$field] = $data;
}
}
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 [▶]
]
]
]
I have following collection:
array:2 [▼
0 => array:21 [▼
"id" => 1
"referrer" => "Kariane Muller DVM"
"path" => null
"tracking_code_id" => 30
"sales" => 2
"field_name" => "ssn"
"income" => 4.0
"fsId" => "1b5e4434-da5a-342e-9b87-df9791b1bcc1"
]
2 => array:21 [▼
"id" => 1
"referrer" => "Kariane Muller DVM"
"path" => null
"tracking_code_id" => 30
"sales" => 1
"field_name" => "income"
"income" => 1.0
"fsId" => "1b5e4434-da5a-342e-9b87-df9791b1bcc1"
]
For visibility purposes I have converted it to array.
How can I collapse this collection into one collection, but I want to
sum the income keys into one in final collection.
Other keys should be included as they are ?
I would start with reduce. If I am understanding correctly you basically want the original collection intact but the income to be summed and reflected in every item.
$summedIncome = $collection->reduce(function ($carry, $item) {
$income = $carry->has('income') ? ($item->income + $carry->income) : $item->income;
$carry->push($item);
$carry->each->income = $income;
return $carry;
}, collect([]));