Im not sure if the question title is correct but what I wanna do is clear in the example below
I have 3 arrays and I want to store data in one table
the table structure is like this
table name: tour_transports
id
transport_id
transport_track
transport_note
arrays coming from blade
"transport_id" => array:2 [
1 => "1"
5 => "5"
]
"transport_track" => array:3 [
1 => " from airport to the hotel"
3 => null
5 => " be ready at 4:pm"
]
"transport_note" => array:3 [
1 => "from hotel to the beach"
3 => null
5 => " bring ur swiming suite"
]
so as you see the ids are 1 and 5 so I wanna store two rows here
id = 1,transport_id = 1 , transport_track = from airport to the hotel , transport_note = be ready at 4:pm
id = 2,transport_id = 5, transport_track = from hotel to the beach , transport_note = bring ur swiming suite
I tried to do this but can't get it correct
if(!empty($request->transport_id))
{
foreach ($request->transport_id as $key => $transport_id) {
foreach ($request->transport_track as $key => $track) {
foreach ($request->transport_note as $key => $transport_note) {
TourTransport::create([
'transport_id' =>$transport_id,
'transport_track' =>$track[$transport_id],
'transport_note' =>$transport_note[$transport_id]
]);
}
}
}
}
You can use this code to achieve your results:
$data = $request->only('transport_id', 'transport_track', 'transport_note');
foreach ($data['transport_id'] as $key => $transportId) {
TourTransport::create([
'transport_id' => $transportId,
'transport_track' => $data['transport_track'][$key],
'transport_note' => $data['transport_note'][$key],
]);
}
Now $results contains the required data. However the better solution might be to configure your html form to send related data in single array entry, Like:
<input type="text" name="transports[0][transport_id]">
<input type="text" name="transports[0][transport_track]">
<input type="text" name="transports[0][transport_note]">
<input type="text" name="transports[1][transport_id]">
<input type="text" name="transports[1][transport_track]">
<input type="text" name="transports[1][transport_note]">
Which you can also use Javascript/php loops to generate the form inputs. Then you will receive form data in server side in well formed structure like:
"transports" => array:2 [
[
'transport_id' => 1,
'transport_track' => 'from airport to the hotel',
'transport_note' => 'be ready at 4:pm',
],
[
'transport_id' => 5,
'transport_track' => 'from hotel to the beach',
'transport_note' => ' bring ur swiming suite',
],
]
Related
My query result returns an array that contains rows with company's structure (group/department/team) as columns and several other data columns, for example:
[
0 => [
group => "g1",
department => "d1",
team => null,
data_col1 => "some_data1",
data_col2 => "some_data2"
],
1 => [
group => "g1",
department => "d1",
team => null,
data_col1 => "some_data3",
data_col2 => "some_data4"
],
2 => [
group => "g1",
department => "d1",
team => "t3",
data_col1 => "some_data5",
data_col2 => "some_data6"
3 => [
group => "g4",
department => "d6",
team => "t11",
data_col1 => "some_data7"
data_col2 => "some_data8"
]
]
I want to "group" the results into an array with common group/department/team so that I can treat all the results with common group/department/team as single row and get the data from them in the same iteration.
The expected structure would be similar to:
[
0 => [
group => "g1",
department => "d1",
team => null,
data => [
0 => [data_col1 => "some_data1", data_col2 => "some_data2"],
1 => [data_col1 => "some_data3", data_col2 => "some_data4"]
],
1 => [
group => "g1",
department => "d1",
team => "t3",
data => [
0 => [data_col1 => "some_data5", data_col2 => "some_data6"]
],
2 => [
group => "g4",
department => "d6",
team => "t11",
data => [
0 => [data_col1 => "some_data7", data_col2 => "some_data8"]
]
]
How can I convert the original array to the desired one, or it's not efficient to do that? (i.e. to perform some demanding task to restructure the array). What would be the best thing to treat the rows with common group/department/team as the same row?
This is a requirement to summarize individual records into groups. The data needs to be reformatted in each group.
Method: By using a 'read ahead' technique we can remove the need to test each record to find out whether to add it to the current group or start a new group. The data is already ordered by team. We just need to iterate over each complete group in turn and append to the output.
The main point about the 'read ahead' technique is that read the next record immediately after you have processed it. This normally means that you cannot use a foreach loop as you often need to read a record before the end of the loop.
The code provided has O(n) runtime.
Note the code is commented to try and make it clear what is happening. The code is very basic PHP. It should work on all versions 5.6 and above I have tested it on 8.1.12.
Test: https://onlinephp.io/c/f8e59
<?php
$inputList = loadTestData();
print_r($inputList);
// -------------------------------------------------
// Output - Team data by: Group - Department - Team
// -------------------------------------------------
$outputList = array();
// -------------------------------------------------------------------------
// State
//
// $currentTeamKey: This is the full key of the current team being processed
// ------------------------------------------------------------------------- */
$groupTeamKey = [];
// The current team record being processed
$currentTeamDetails = null;
// -------------------------------------------------
// o Initialize Iterator
// o Read Ahead
// ------------------------------------------------- */
reset($inputList);
$currentTeamDetails = current($inputList); // always have a record to process
// -------------------------------------------------
// Control
// -------------------------------------------------
while ($currentTeamDetails !== false) { // end of input?
// Process ONE Team completely -- there must be at least one record in the group and it is ready to process
$groupTeamKey = getTeamKey($currentTeamDetails);
$groupTeamData = [];
// accumulate all the team data for the current team
while ( $currentTeamDetails !== false // end of input
&& $groupTeamKey === getTeamKey($currentTeamDetails)) {
// Do not need to know the names of the data columns or the number of them.
$groupTeamData[] = getTeamDataRow($currentTeamDetails, $groupTeamKey);
$currentTeamDetails = next($inputList); // read ahead
}
// add the team data to the current key and append to the output
$groupTeamKey['data'] = $groupTeamData;
$outputList[] = $groupTeamKey;
}
// -------------------------------------------------
print_r($outputList);
exit;
// -------------------------------------------------
// subroutines
// -------------------------------------------------
// -------------------------------------------------
// Team Full Key: <group> <dept> <team>
//
function getTeamKey(array $teamDetails = null)
{
return [ 'group' => $teamDetails['group'],
'department' => $teamDetails['department'],
'team' => $teamDetails['team'],
];
}
// -------------------------------------------------
// Team Data as 1 row
// Assume you don't know the data column names but you do know the keys!
//
function getTeamDataRow(array $teamDetails, array $currentTeamKey)
{
$allDataRows = array_diff_assoc($teamDetails, $currentTeamKey);
$dataRow = [];
foreach ($allDataRows as $key => $value) {
$dataRow[$key] = $value;
}
return $dataRow;
}
//-------------------
// Test Data
//
function loadTestData()
{
return [
0 => [
'group' => "g1",
'department' => "d1",
'team' => null,
'data_col1' => "some_data1",
'data_col2' => "some_data2",
],
1 => [
'group' => "g1",
'department' => "d1",
'team' => null,
'data_col1' => "some_data3",
'data_col2' => "some_data4",
],
2 => [
'group' => "g1",
'department' => "d1",
'team' => "t3",
'data_col1' => "some_data5",
'data_col2' => "some_data6",
],
3 => [
'group' => "g4",
'department' => "d6",
'team' => "t11",
'data_col1' => "some_data7",
'data_col2' => "some_data8",
],
];
}
This question already has answers here:
Merge two arrays into one associative array
(2 answers)
Closed 7 months ago.
I want to change the following php array
"extra_charge_item" => [
0 => "Massage",
1 => "Pool table",
2 => "Laundry"
],
"extra_charge_description" => [
0 => "Paid",
1 => "Paid",
2 => "We wash everything"
],
"extra_charge_price" => [
0 => "200",
1 => "100",
2 => "1000"
],
I haven't been able to solve for a whole 2hrs
This is the expected output
"new_data" => [
0 => [
"Maasage", "Paid", "200"
],
1 => [
"Pool table", "Paid", "100"
],
2 => [
"Laundry", "we wash everything", "1000"
]
]
Rather than doing all the work for you, here's some pointers on one way to approach this:
If you are happy to assume that all three sub-arrays have the same number of items, you can use array_keys to get those keys from whichever you want.
Once you have those keys, you can use a foreach loop to look at each in turn.
For each key, use square bracket syntax to pluck the three items you need.
Use [$foo, $bar, $baz] or array($foo, $bar, $baz) to create a new array.
Assign that array to your final output array, using the key from your foreach loop.
Just use foreach with key => value
$data = [
"extra_charge_item" => [
0 => "Massage",
1 => "Pool table",
2 => "Laundry"
],
"extra_charge_description" => [
0 => "Paid",
1 => "Paid",
2 => "We wash everything"
],
"extra_charge_price" => [
0 => "200",
1 => "100",
2 => "1000"
],
];
$newData = [];
foreach ($data as $value) {
foreach ($value as $k => $v) {
$newData[$k][] = $v;
}
}
var_dump($newData);
I found an answer. Seems someone else had the same problem
Merge two arrays into one associative array
Here's the solution for my case;
//These are arrays passed from front end in the name attribute e.g extra_charge_item[] e.t.c
$extra_charge_item_array = $request->input('extra_charge_item');
$extra_charge_description_array = $request->input('extra_charge_description');
$extra_charge_price_array = $request->input('extra_charge_price');
$new_extra_charges_data = array_map(
function ($item, $description, $price) {
return [
'item' => $item,
'description' => $description,
'price'=> $price
];
}, $extra_charge_item_array, $extra_charge_description_array, $extra_charge_price_array);
//save the data
foreach ($new_extra_charges_data as $extra_charge) {
Charge::create([
'item' => $extra_charge['item'],
'description' => $extra_charge['description'],
'price' => $extra_charge['price']
]);
}
How can I convert the data I send with post to php code?
I have 3 select fields. adult, child, baby.
I want to create the following json structure up to the number of rooms when I post. The number of children and babies is not correct by area. How can I do it?
foreach ($this->input->post('adult') as $key => $value) {
$rooms[] = array(
'adult' => $_POST['adult'][$key],
'child' => array(
'child_total' => $_POST['child'][$key],
'child_date' => $_POST['child_date']
),
'baby' => array(
'baby_total' => $_POST['baby'][$key],
'baby_date' => null
)
);
}
I want to this json...
rooms: [
{
adult: 2,
child: [
child_total: 1
child_date: [
"2017-08-10"
],
],
baby: [
baby_total: 1
baby_date: [
"2017-07-01"
],
],
},
{
adult: 1,
child: [
child_total: 2
child_date: [
"2017-08-08",
"2017-08-09"
],
],
baby: [
baby_total: 2
baby_date: [
"2017-06-08",
"2017-05-09"
],
],
}
],
To figure out the data structure needed to make you json encoded string, let's start by defining the objects you're working with. Assuming this is something like a hotel booking system, let's map it out:
A hotel has rooms. They are identified by room number. This can be illustrated in code by $room[$room_number]. Using the room number as the key allows you to uniquely identify a particular room.
Each room has occupants: adults, children, and babies. This can be illustrated in code by
$room[$room_number]['adults']
$room[$room_number]['children']
$room[$room_number]['babies']
The set of babies can be illustrated as $baby[]. We really don't need to identify the baby with a unique identifier other that the index number; we're just interested in the list.
So, let's replace ['babies'] with ['baby'][]
$room[$room_number]['adults']
$room[$room_number]['children']
$room[$room_number]['baby'][]
Each baby has attributes. We're only going to use one, but for the sake of example, let's say we want to record two: birthdate and name. Another way of saying that would be each $baby = array('birthday'=>$birthdate, 'name'=>$name);
This is a little harder to illustrate, since you have to gather all the babies information before you assign it to $room[$room_number]['baby'][]. So I will show it using the index number:
$room[$room_number]['adults']
$room[$room_number]['children']
$room[$room_number]['baby'][0]['birthdate']
$room[$room_number]['baby'][0]['name']
The same functionality is desired for children:
$room[$room_number]['adults']
$room[$room_number]['children'][0]['birthdate']
$room[$room_number]['children'][0]['name']
$room[$room_number]['baby'][0]['birthdate']
$room[$room_number]['baby'][0]['name']
See a pattern? [identifier][attribute][identifier][attribute]
With this data structure, we can build your html inputs, assuming 2 children and 2 babies:
<?php
// assuming room number is 123
$room_number = '123';
?>
<!-- child 1 name -->
<label><input name="room[<?= $room_number ?>]['child'][0]['name']">Child 1 name</label>
<!-- child 1 birthdate -->
<label><input name="room[<?= $room_number ?>]['child'][0]['birthdate']">Child 1 birthdate</label>
<!-- child 2 name -->
<label><input name="room[<?= $room_number ?>]['child'][1]['name']">Child 2 name</label>
<!-- child 2 birthdate -->
<label><input name="room[<?= $room_number ?>]['child'][1]['birthdate']">Child 2 birthdate</label>
When you receive these inputs in your php script, it will already be properly formed as an array (I'm excluding adults and filled in sample values):
php > $room_number='123';
php > $room[$room_number]['child'][0]['birthdate'] = '20010-01-01';
php > $room[$room_number]['child'][0]['name'] ='Junior';
php > $room[$room_number]['child'][1]['birthdate'] = '2019-01-01';
php > $room[$room_number]['child'][1]['name'] = 'Bubba';
php > print_r($room);
Array
(
[123] => Array
(
[child] => Array
(
[0] => Array
(
[birthdate] => 20010-01-01
[name] => Junior
)
[1] => Array
(
[birthdate] => 2019-01-01
[name] => Bubba
)
)
)
)
This can easily be fed into json_encode: print json_encode($room);
However, you might ask what about the counts (totals)?
Those can easily be figured from the array structure, so they don't really need to be included:
php > print count($room[$room_number]['child']);
2
php >
You can use the json_encode function like this:
json_encode(['rooms' => $rooms])
I'm trying to get a well-better formated list of information.
Basically what I have right now is a multi dimensional array that has multiple entries in it with different data.
If I would do foreach $bigarray, I would get something like this:
array(
"id" => 1,
"company" => "bar",
"advertisment" => "Selling X",
"user_id" => "200",
"uri" => "bbbbbbxa"
);
array(
"id" => 2,
"company" => "bar",
"advertisment" => "Selling ABC",
"user_id" => "200",
"uri" => "xxxaaaa"
);
array(
"id" => 3,
"company" => "CROMUS",
"advertisment" => "Selling BBB",
"user_id" => "222",
"uri" => "bsaxxaa"
);
** notice the same user_id and company name **
** I want a unique list of companies with ads corresponding to it **
From the above I would get 3 'squares' of data like this:
Company Name
Advertisment Title
================
Same Company Name
Same advertisment title
================
Different Company Name
Different advertisment title
=========================
but I would want to get:
=========================
Company Name
first advertisment title
second advertisment title
** so on if any other entries with same user_id are found **
=========================
Different Company Name
Different Advertisment
=========================
So basically I would want array 1 to add somehow to array 0 so when I echo in the foreach($bigarray as $post), I go something like
echo $post['advertisment'].' '.$post['uri']
echo $post['advertisment_2'].' '.$post['uri2']
Note: I might have more than 2 values , I might have 6 ads on the same company and I basically want to organise them by the id (the top one would be the newest)
Until now I did something like this just to realise i took the wrong approach:
foreach($latest->posts as $key => $post) {
if(in_array($post->user_id,$iduri)){
array_push($iduri, $post->user_id);
}
if(in_array($post->user_id,$iduri)) {
array_push($cuie,$post->title);
array_push($urix,$post->uri);
} else {
for ($i = 0; $i <= count($cuie); $i++) {
echo $cuie[i];
echo $urix[i];
}
} // end if in array
} //end foreach
I want to dynamically create a short array with a list of objects. This is for a POST request with the Guzzle client. That's why I need it in a short array.
example of a Guzzle post request:
$res = $this->client->request($methode, $request_url, [
'form_params' => [
'param' => 'value'
]
]);
Problem case:
I have got a List: Params of Objects: Param.
Param has three attributes id, name, link_id.
Let's say the List has three Object.
param(1, email, 1)
param(2, username, 1)
param(3, password, 1)
I want to dynamically create from the list an array with the short array syntax.
Example(Pseudo):
for each params as param
[
'form_params' => [
param->name => 'value'
]
]
the result of this code will be like this
[
'form_params' => [
'email' => 'value',
'username' => 'value',
'password' => 'value'
]
]
Code example:
$params = array(
"param" => array (
"id" => "1",
"name" => "username",
"link_id" => "1",
)
);
$value = '';
$shortarray = '';
foreach($params as $key => $param){
$shortarray .= $param->name . '=>' . $value . ',';
}
$postParams = ['form_params' => [ . $shortarray . ]];
I really could use some help. Thank you in advance.
If you want to just show short array syntax than this solution may helps you to resolve you problem.
https://stackoverflow.com/a/35207172/4781882
I am not quite sure why you require it be a "short array", but here's a solution...
I assume this is a web form, yes?
So let's assume you name your forms in a way that is usable, like:
<form method="POST" action="yourform.html">
Line 1 <input name="email1"> | <input name="user1"> | <input name="password1">
<br/>-------<br/>
Line 2 <input name="email2"> | <input name="user2"> | <input name="password2">
<br/>-------<br/>
Line 3 <input name="email3"> | <input name="user3"> | <input name="password3">
</form>
Then...
for($i = 1; $i <= 3; $i++ {
$postparms[] = ['email' => $_POST['email'.$i], 'user' => $_POST['user'.$i], 'password' => $_POST['password'.$i] ];
}
print_r($postparms);