Laravel merge arrays into one array - php

I am sending 4 arrays to my controller that they need to combine before I can store them to database, here is how they're look like:
array:4 [▼
"from" => array:7 [▼
0 => "8:00"
1 => null
2 => null
3 => null
4 => null
5 => null
6 => null
]
"to" => array:7 [▼
0 => "21:00"
1 => null
2 => null
3 => null
4 => null
5 => null
6 => null
]
"closed" => array:6 [▼
0 => "on"
1 => "on"
2 => "on"
3 => "on"
4 => "on"
5 => "on"
]
"day_id" => array:7 [▼
0 => "a0275acb-c6e5-428f-8589-da0644c1f42e"
1 => "9a8d2dc5-fbe5-4a93-a279-2c6a90781777"
2 => "84d74f04-3728-4314-a6e7-8710cecaa911"
3 => "79ef140a-5de5-4b27-a286-9893cbac820e"
4 => "6d0b2858-ff96-46ce-ae1b-665c3ee353aa"
5 => "38225fe6-3bce-4ee9-bad8-c7f6cacc4854"
6 => "28cef2be-1ff6-4e80-b322-a208f4838391"
]
]
As you might notice closed array is less by 1 value as the checkbox was unchecked, so this one is vary between no value (if none are check) to 7 values (if all of them are checked)
Anyway, I need to make this arrays to something like this:
array:7 [▼
"finaldata" => array:4 [▼
from => "8:00"
to => "21:00"
closed => off
day_id => "a0275acb-c6e5-428f-8589-da0644c1f42e"
],
"finaldata" => array:4 [▼
from => null
to => null
closed => on
day_id => "9a8d2dc5-fbe5-4a93-a279-2c6a90781777"
],
// and so on...
]
If I can get such result then I'll be able to loop and store this data into my database.
Code
$schedules = [];
$schedules['from'] = $request->input('from');
$schedules['to'] = $request->input('to');
$schedules['closed'] = $request->input('closed');
$schedules['day_id'] = $request->input('day_id');
dd($schedules); // returning my results above (on top)
foreach($schedules as $schedule) {
$days = new WorkDays;
//...
$days->save();
}
Question
How can I get such result as I shared to store my data?
Update
blade
<div class="mt-4">
<div x-data="handler()">
<x-jet-label value="Schedule" />
<table class="itable align-middle w-full">
<thead class="thead-light">
<tr>
<th>Day</th>
<th>From</th>
<th>To</th>
<th>Closed</th>
</tr>
</thead>
<tbody>
<template x-for="(field, index) in {{$days}}" :key="index">
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" name="from[]" />
<x-jet-input x-model="field.id" type="hidden" value="field" name="day_id[]"/>
</td>
<td><x-jet-input x-model="field.to" type="text" name="to[]" /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" name="closed[]" /></td>
</tr>
</template>
</tbody>
</table>
</div>
<script>
function handler() {
return {
fields: []
}
}
</script>
</div>
Update 2
based on iCoders answer this is what i get, which is good but the ones with unchecked checkbox will not have closed variable array 0 and 6.
"data" => array:7 [▼
0 => array:3 [▼
"from" => "54"
"day_id" => "a0275acb-c6e5-428f-8589-da0644c1f42e"
"to" => "474"
]
1 => array:4 [▼
"from" => null
"day_id" => "9a8d2dc5-fbe5-4a93-a279-2c6a90781777"
"to" => null
"closed" => "on"
]
2 => array:4 [▼
"from" => null
"day_id" => "84d74f04-3728-4314-a6e7-8710cecaa911"
"to" => null
"closed" => "on"
]
3 => array:4 [▼
"from" => null
"day_id" => "79ef140a-5de5-4b27-a286-9893cbac820e"
"to" => null
"closed" => "on"
]
4 => array:4 [▼
"from" => null
"day_id" => "6d0b2858-ff96-46ce-ae1b-665c3ee353aa"
"to" => null
"closed" => "on"
]
5 => array:4 [▼
"from" => null
"day_id" => "38225fe6-3bce-4ee9-bad8-c7f6cacc4854"
"to" => null
"closed" => "on"
]
6 => array:3 [▼
"from" => "67565"
"day_id" => "28cef2be-1ff6-4e80-b322-a208f4838391"
"to" => "6567"
]

I dont know much usage about new component in laravel 8 but usually common idea is
#foreach($days as $key=>$value)
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" name="data[{{$key}}][from]" />
<x-jet-input x-model="field.id" type="hidden" value="field" name="data[{{$key}}][day_id]"/>
</td>
<td><x-jet-input x-model="field.to" type="text" name="data[{{$key}}][to]" /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" name="data[{{$key}}][closed]" /></td>
</tr>
#endforeach
Then in controller if you dd($request->data) you get merged data
Updated
As per another question answer Dynamically set name attribute of input field in loop with AlpineJS
You need to use x-bind:name with a template string:
<template x-for="(field, index) in {{$days}}" :key="index">
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" x-bind:name="`data[${index}][from]`/>
<x-jet-input x-model="field.id" type="hidden" value="field" x-bind:name="`data[${index}][day_id]`"/>
</td>
<td><x-jet-input x-model="field.to" type="text" x-bind:name="`data[${index}][to]` /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" x-bind:name="`data[${index}][closed]` /></td>
</tr>
</template>
Update2:
<input x-model="field.closed" class="form-checkbox" type="checkbox" name="data[{{$key}}][closed]" #click="$event.target.value = $event.target.checked ? '1' : '2'"/>

Change your blade to something like this.
<template x-for="(field, index) in {{$days}}" :key="index">
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" name="finaldata[{{$loop->iteration}}]['from']" />
<x-jet-input x-model="field.id" type="hidden" value="field" name="finaldata[{{$loop->iteration}}]['day_id']"/>
</td>
<td><x-jet-input x-model="field.to" type="text" name="finaldata[{{$loop->iteration}}]['to']" /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" name="finaldata[{{$loop->iteration}}]['closed']" /></td>
</tr>
</template>

Related

Convert Array data to html table

im having some issues with a array data that i got form a json file, but i guess the issue maybe is with the json structure that that i converted in array using json decode and file_get_contents.
Basicall this is the array strucutre:
#items: array:4 [▼
"Monday, 1 de Fev de 2021" => array:5 [▼
"PM" => array:7 [▼
1 => "1140-10"
2 => "8498-25"
3 => "7076-19"
4 => "3380-20"
5 => "8194-24"
6 => "8288-22"
7 => "687-22"
]
"PT" => array:7 [▼
1 => "6406-2"
2 => "2976-19"
3 => "6029-8"
4 => "8130-8"
5 => "7530-8"
6 => "1071-18"
7 => "064-16"
]
"PTV" => array:7 [▶]
"PTN" => array:7 [▶]
]
"Sat, 31 de Jan de 2021" => array:2 [▼
"PTM" => array:7 [▶]
"PT" => array:7 [▶]
]
Basically the date is the table caption, and the index with the letters eg: "PTV","PM","PT"...", are the theader th titles.
And inside of the "PM" for example there are some results:
1 => "1140-10"
2 => "8498-25"
3 => "7076-19"
4 => "3380-20"
5 => "8194-24"
6 => "8288-22"
7 => "687-22"
Where the indexes (1,2,3..) Are the prize, and the values after each index are the results.
I need to construct my table to be like this image above
This is my code:
#if(sizeof($results) > 0)
#foreach($results as $date => $result)
<div class="col-xl-12">
<table class="table">
<caption>
{{ $date }}
</caption>
<thead>
<tr>
<th id="hoje" class="tabla-header"></th>
#foreach($result as $banca => $re)
<th id="{{ $banca }}" class="tabla-header">{{ $banca }}</th>
#endforeach
</tr>
</thead>
<tbody>
{{ sizeof($result) }}
#for ($i = 0; $i < 7; $i++)
<tr>
<td>1</td>
#for ($n = 0; $n < sizeof($result); $n++)
<td>{{ $result[] }}/td>
#endfor
</tr>
#endfor
</tbody>
</table>
</div>
#endforeach
#endif
create a database and insert into table information . next with console make:controller // make a controller
make a method ...( select information of database)
$var1 = DB::table("table_name")->get('column_1');// first use DB namespace
$var2 = DB::table("table_name")->get('column_2');
$var2 = $var2[
// and other get columns table
return view('view_name',['tr1' => $var1,'tr2' => $var2 /* and etc */);
}
and view is under code
<!DOCTYPE htl>
<html>
<table class="table"> <!-- table class ; you create a table class in your code -->
<tr>
<th>{{$var1[0][0]->column_name}}</th>
<th>{{$var1[0][1]->column_name}}</th>
<th>{{$...}}</th>
</tr>
<tr>
<th> {{$avr2[0][0]->column_name}} </th>
<th> {{$var2[0][1]->coumn_name}} </th>
<!-- and continue above code -->
</tr>
</table>
</html>
first you select info of db and show them in view

undefined index 'value' in laravel

im using laravel 7 and trying to get datas from api use http.
when i use dd('$datas'),i got this
array:1 [▼"manajemen_sdm" => array:4 [▼ 0 => array:9 [▼ "id_karyawan" => "2" "nama" => "Koko Hendriko" "gender" => "Laki-Laki" "ttl" => "1998-04-07" "alamat" => "Kp.Palasari " "no_telp" => "821863141" "email" => "kokohendriko#gmail.com" "npwp" => "89678923652" "golongan" => "B" ] 1 => array:9 [▶] 2 => array:9 [▶] 3 => array:9 [▶] ] ]
my controller
public function index()
{
$datas = Http::get('https://projectsoadenis.000webhostapp.com/api')->json();
return view('sdm.index',compact('datas'));
}
view
#foreach ($datas as $datasdm)
<tr>
<td>{{$no++}}</td>
<td>{{$datasdm['id_karyawan']}}</td>
<td>{{$datasdm['nama']}}</td>
<td>{{$datasdm['gender']}}</td>
<td>{{$datasdm['ttl']}}</td>
<td>{{$datasdm['alamat']}}</td>
<td>{{$datasdm['no_telp']}}</td>
<td>{{$datasdm['email']}}</td>
<td>{{$datasdm['npwp']}}</td>
<td>{{$datasdm['golongan']}}</td>
</tr>
#endforeach
If you look at the data you are getting back from the API, your data is actually nested inside objects that live under a manajemen_sdm property.
Your loop should work correctly if you update it to loop over the manajemen_sdm key:
#foreach ($datas['manajemen_sdm'] as $datasdm)
<tr>
<td>{{$no++}}</td>
<td>{{$datasdm['id_karyawan']}}</td>
<td>{{$datasdm['nama']}}</td>
<td>{{$datasdm['gender']}}</td>
<td>{{$datasdm['ttl']}}</td>
<td>{{$datasdm['alamat']}}</td>
<td>{{$datasdm['no_telp']}}</td>
<td>{{$datasdm['email']}}</td>
<td>{{$datasdm['npwp']}}</td>
<td>{{$datasdm['golongan']}}</td>
</tr>
#endforeach

How do I merge an array with PHP Laravel?

I have cloned HTML prepared with input group. Some checkbox and radio are not selected. I want to push into the selected email.
I've tried many methods.
array_merge()
array_combine()
array_push()
array_merge_recursive()
But none of these worked. Or I don't know how to get them to work.
HTML
<div class="form-group">
<label for="name">E-posta</label>
<div class="input-group">
<input type="email" class="form-control email-address" name="email[]" placeholder="E-Posta giriniz">
<div class="btn-group">
<label class="btn btn-default">
<input class="primary-radio" type="radio" name="primary[]" checked autocomplete="off"> <span
class="fas fa-star"></span>
</label>
<label class="btn btn-default">
<input class="ban-checkbox" type="checkbox" name="ban[]" autocomplete="off"> <span
class="fas fa-ban"></span>
</label>
<label class="btn btn-default">
<input class="invalid-checkbox" type="checkbox" name="invalid[]" autocomplete="off"> <span
class="fas fa-exclamation-circle"></span>
</label>
</div>
</div>
</div>
PHP
public function add(Request $request)
{
$emails = $request->input('email');
$primary = $request->input('primary');
$ban = $request->input('ban');
$invalid = $request->input('invalid');
$emailAddresses = array();
foreach ($emails as $emailKey => $emailValue) {
$emailAddresses[$emailKey] = [
'emailAddress' => $emailValue,
'invalid' => $invalid,
'lower' => $emailAddresses,
'ban' => $ban,
'primary' => $primary
];
}
dd($emailAddresses);
}
Output
array:3 [▼
0 => array:5 [▼
"emailAddress" => "dodis#live.com"
"invalid" => null
"lower" => "dodis#live.com"
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
"primary" => array:1 [▼
0 => "on"
]
]
1 => array:5 [▼
"emailAddress" => "test#live.com"
"invalid" => null
"lower" => "test#live.com"
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
"primary" => array:1 [▼
0 => "on"
]
]
2 => array:5 [▼
"emailAddress" => "bundayok#live.com"
"invalid" => null
"lower" => "bundayok#live.com"
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
"primary" => array:1 [▼
0 => "on"
]
]
]
Such an output comes. It shouldn't be like that. Here's the example I want it to be.
0: {
emailAddress: "bilgi#ekinciler.com.tr"
invalid: false
lower: "bilgi#ekinciler.com.tr"
optOut: false
primary: true
}
1: {
emailAddress: "muhasebe#ekinciler.com"
invalid: false
lower: "muhasebe#ekinciler.com"
optOut: false
primary: false
}
I am sorry for my English. I hope I can. I would be glad if you help.
Try below code,
What I have done is added array index to each loop to get correct value of that index, here your
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
is array itself so you need 0 index for the first array data. and same applies for all the array.
public function add(Request $request)
{
$emails = $request->input('email');
$primary = $request->input('primary');
$ban = $request->input('ban');
$invalid = $request->input('invalid');
$emailAddresses = array();
$i = 0;
foreach ($emails as $emailKey => $emailValue) {
$emailAddresses[$emailKey] = [
'emailAddress' => $emailValue,
'invalid' => $invalid[$i]?$invalid[$i]:'',
'lower' => $emailAddresses,
'ban' => $ban[$i]?$ban[$i]:'',
'primary' => $primary[$i]?$primary[$i]:''
];
$i++;
}
dd($emailAddresses);
}

How to get each question_id and answer from the array?

If the user is doing a registration in a conference, and is registering 1 participants in the registration type with id "1" (Jake K), and 1 participant in the regitration type with id "4" (John W), the request with the form data has this 3 arrays:
"name" => array:2 [▼
1 => array:1 [▼
1 => "Jake"
]
4 => array:1 [▼
1 => "John"
]
]
"surname" => array:2 [▼
1 => array:1 [▼
1 => "K"
]
4 => array:1 [▼
1 => "W"
]
]
"answer" => array:1 [▼
1 => array:1 [▼
1 => array:2 [▼ // answers answered for the registration_type_id 1
1 => "answer1"
2 => "answer2"
]
]
]
Is necessary to use the info of this array to insert in the participants and answers table. Its inserting correctly in the participants table but for the answers table is not working:
foreach ($request->all()['name'] as $key => $nameArray) {
foreach ($nameArray as $nameKey => $name) {
// this is working
$participant_result = Participant::create([
'name' => $name,
'surname' => $request['surname'][$key][$nameKey],
'registration_id' => $registration->id,
'registration_type_id' => $key
]);
// save answer to Database if exist
// this is not working
$answer = Answer::create([
'question_id' => $request['answer'][$key], // the issue is here
'participant_id' => $participant_result->id,
'answer' => $request['answer'][$key][$nameKey], // and here
]);
}
}
The issue is because is necessary to insert in the question_id and answer columns of the answers table. But this values are not returned correctly from the array with "$request['answer'][$key]" and "$request['answer'][$key][$nameKey]".
Do you know how to properly get the question id and answer from the array?
In this above array example, the question id of the "answer1" is 1 and the id of the "answer2" is 2.
"answer" => array:1 [▼
1 => array:1 [▼
1 => array:2 [▼
1 => "answer1"
2 => "answer2"
]
]
Form:
<form method="post"
action="https://proj.test/conference/1/conf-test/registration/storeRegistration">
<h6> Participant - 1 - general</h6>
<div class="form-group">
<label for="namegeneral_1">Name</label>
<input type="text" required id="namegeneral_1" name="name[1][1]" class="form-control" value="">
</div>
<div class="form-group">
<label for="surnamegeneral_1">Surname</label>
<input type="text" id="surnamegeneral_1" class="form-control" name=" surname[1][1]" value="">
</div>
<div class="form-group">
<label for="participant_question">Question 1</label>
<input type='text' name='answer[1][1][1]' class='form-control' required>
<input type="hidden" name="question_required[1][1]" value="1">
</div>
<div class="form-group">
<label for="participant_question">Question 2</label>
<textarea name='answer[1][1][2]' class='form-control' rows='3' required></textarea>
<input type="hidden" name="question_required[1][2]" value="1">
</div>
<h6> Participant - 1 - plus</h6>
<div class="form-group">
<label for="nameplus_1">Name</label>
<input type="text" required id="rnameplus_1" name="rname[4][1]" class="form-control" value="">
</div>
<div class="form-group">
<label for="surnameplus_1">Surname</label>
<input type="text" id="rsurnameplus_1" class="form-control" name=" rsurname[4][1]" value="">
</div>
<input type="submit" class="btn btn-primary" value="Register"/>
</form>
Firstly: in loop you have more than one name, but answer has one key (1). On second run you have $key == 4, but not have this in $request['answer']. Maybe inside first loop you shoud have two loops? One for registering participants and one for registering answers? If answers are registered for both, build array with $participantResult and for every answer register count($participantResult) answers :O If not, remember ID only for first registered participant and save answer.
Please tell me how $request['answer'] works? What is $request['answer'][1] and what $request['answer'][1][1]?
Secondly $request['answer'][$key][$nameKey] in this case is array of two elements. If Answer::create knows about it - it's no problem ;)
EDIT
Is this right solution?
<?php
$aPID = [];
foreach ($request->all()['name'] as $key => $nameArray) {
foreach ($nameArray as $nameKey => $name) {
$aPID[$key] = Participant::create([
'name' => $name,
'surname' => $request['surname'][$key][$nameKey],
'registration_id' => $registration->id,
'registration_type_id' => $key
]);
}
}
foreach($request['answer'] as $pid => $answersArray) {
foreach($answersArray as $questionId => $answer) {
$answer = Answer::create([
'question_id' => $questionId,
'participant_id' => $aPID[$pid],
'answer' => $answer,
]);
}
}

Looping through array containing arrays

I have completely changed the format of my array now, and I had what I hope is a simple misunderstanding on my part. So my array now looks like the following
array:9 [▼
0 => array:4 [▼
"leadData" => array:7 [▼
"LeadID" => "1232806"
"Client" => "Some Client"
"LeadName" => "Test"
"Owner" => "Someone"
"Value" => "2160.00"
]
"clientData" => array:2 [▼
"Prospect" => "No"
]
"quoteData" => array:8 [▼
"QuoteID" => "Q0020"
"ProjectName" => "Test"
"Amount" => "1234"
]
"customData" => array:2 [▼
0 => array:1 [▼
"Type" => "New"
]
1 => array:1 [▼
"Month" => "June 16"
]
]
]
2 => array:4 [
...
]
]
So it is essentially now 4 inner arrays. Now if I do the following, I can print out all the data for the leadData inner array
foreach($leadArray as $array)
<tr>
foreach($array['leadData'] as $leadKey => $leadData)
<td>
{{ $leadData }}
</td>
endforeach
</tr>
endforeach
That works fine. However, I only want to display certain parts of this array. I would have presumed doing something like the following would work
foreach($leadArray as $array)
<tr>
foreach($array['leadData'] as $leadKey => $leadData)
<td>
{{ $leadData['LeadID'] }}
</td>
<td>
{{ $leadData['LeadName'] }}
</td>
endforeach
</tr>
endforeach
However if I do this I get and Illegal String Offset error. Is this not how I would access this data?
p.s. Ignore the way I do the foreach loop etc, this is because I am using a template engine.
Thanks
You don't have to loop over the second array, you can use the keys to get the data.
foreach($leadArray as $array)
<tr>
<td>
{{ $array['leadData']['LeadID'] }}
</td>
<td>
{{ $array['leadData']['LeadName'] }}
</td>
</tr>
endforeach
Your main array will be like this, where you want to work, right?
<pre>
$aMainArray = array(
0 => array(
"leadData" => array(
"LeadID" => "1232806",
"Client" => "Some Client",
"LeadName" => "Test",
"Owner" => "Someone",
"Value" => "2160.00",
)
)
);
foreach ($aMainArray AS $aSubArray) {
print_r($aSubArray);
// You can echo your required values like below
echo $aSubArray['leadData']['LeadID'];
echo $aSubArray['leadData']['LeadName'];
// OR like this one
foreach ($aSubArray AS $value) {
echo $value['LeadID'];
echo $value['LeadName'];
}
}
</pre>

Categories