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
Related
so what i have is just some data that should be fixed for printing, and i can't wrap my head around this one...
i have some finished products separated for each batch code (int_lot) with their quantities. You can select and give that values to the invoice, but what i need to do is calculate total of same product name (in relationship called FinishedProduct) and i get all finished products with relation that has quantities with:
DeliveryProductQuantity::where('delivery_note_id', $packingList->delivery_note_id)->with('FinishedProduct')->get();
then i get object like this:
"id" => 12
"finishedid" => "24"
"quantity" => "116"
"old_quantity" => "116"
"delivery_note_id" => "52"
now when i load relationship with first() i get data like for each item in foreach:
"id" => 12
"finished_product_name" => "Product Name"
"shift" => "Prva"
"expiry_date" => "19042023/1"
"user_id" => "6"
What i want to do first is just put all products with same finished_product_name. But finished_product_name is in relation and quantity is in array that's not in relationship.
So i need foreach item of first array of objects to check if relationships product name exists and then if it doesn't add a new entry in temporary array, if does just add quantity to the last one with same product name. What have i tried (besides many else):
$total_data = [];
foreach ($test2 as $product) {
foreach ($product->FinishedProduct as $key => $value) {
if(!in_array($product->FinishedProduct->first()->finished_product_name, $total_data)) {
array_push($total_data,
[
'finished_product_name' => $product->FinishedProduct->first()->finished_product_name,
'expiry_date' => $product->FinishedProduct->first()->expiry_date,
'quantity' => $product->quantity,
'old_quantity' => $product->old_quantity,
'delivery_note_id' => $product->delivery_note_id
]
);
}
if(in_array($product->FinishedProduct->first()->finished_product_name, $total_data)) {
foreach ($total_data as $key => $value) {
if($value['finished_product_name'] == $product->FinishedProduct->first()->finished_product_name) {
$total_data[$key]['quantity'] += $product->quantity;
$total_data[$key]['old_quantity'] += $product->old_quantity;
}
}
}
}
}
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',
],
]
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 want a drop down menu to be able to sort items I have stored in an array on to the page, by the option selected in the drop down menu.
For example if I select nike from the drop down menu only the item in the array with a brand name of nike will show on the page.
<?php
//the data file
$inventory = [];
//shoes
// steph curry
$inventory[100] = [
"name" => "Steph's Clutchfit Drive",
"item" => "Shoes",
"img" => "images/shoes/stephcurry.png",
"brand" => "Under Armour",
"color" => "White , Blue , Yellow",
"category" => "Basketball",
"type" => "High",
"size" => "10 , 12 , 14",
"price" => "$ 80.00"
];
//micheal jordan
$inventory[101] = [
"name" => "Jordan 11's",
"item" => "Shoes",
"img" => "images/shoes/jordan11.png",
"brand" => "Nike",
"color" => "White , Blue , Red",
"category" => "Basketball",
"type" => "High",
"size" => "9 , 11 , 12",
"price" => "$ 110.00"
];
HTML file
when I select nike I want only items from the array list above, with nike to show on the page.
<select>
<option value="nike">nike</option>
<option value="reebok"reebok</option>
<option value="underArmor">UA</option>
</select>
combination of array_search and array_combine can help to search in a
multidimensional array.
If you are having id (index of array) in the value and only one Nike item you want to fetch then this would work:
echo array_search("Nike", array_column($inventory, "brand", "id"));
If you do not have id column and multiple Nike-items can be found then this would work:
print_r(array_keys(array_combine(array_keys($inventory), array_column($inventory, "brand")), "Nike"));
Try and let me know.
I am creating a questionnaire for a client that requires the questions to be organized by 3 layers of levels. I've successfully created the U.I. however I've been trying for the last 3 hours to pull data from a database in such a way that everything loads in the right place. The database is organized like so by the client so i have no control over it:
id description parentId about
1 Level 1 0 This is the top level or in my case tab1
2 Level 2 0 This is the next tab in the top level
3 Level 1a 1 This is the first category under tab1
4 Level 1b 1 This is the next category under tab1
5 Level 1a1 3 This is the content under the first category of tab1
So anything with a parentId of 0 is the top level and will contain anything of the second level with the parentId of 1 and so on. Confusing yes, I can barely make sense of this but this is how I've been told to do it.
What approach would be the best way to execute something like this? An example from another question I'm using as a reference is attached below (although not working)
foreach (mysql_query("SELECT * FROM pB_test ORDER BY id ASC") as $row) {
$menuitem = array_merge(array(), $row);
$menuLookup[$menuitem['id']] = $menuitem;
if ($menuitem['parent'] == null) {
$menuitem['path'] = "/" . $menuitem['name'];
$menu[] = $menuitem[];
} else {
$parent = $menuLookup[$menuitem['parent']];
$menuitem['path'] = $parent['path'] . "/" . $menuitem['name'];
$parent['menu'][] = $menuitem;
}
}
Any help would be greatly appreciated. Cheers
If you have exactly 3 levels, then you can try this:
http://sqlfiddle.com/#!2/70e96/16
(
SELECT 1 AS lvl,
top_level.description AS o1, top_level.id AS id1,
NULL AS o2, NULL AS id2,
NULL AS o3, NULL AS id3,
top_level.*
FROM node AS top_level
WHERE top_level.parentId = 0
)UNION ALL(
SELECT 2 AS lvl,
top_level.description AS o1, top_level.id AS id1,
category_level.description AS o2, category_level.id AS id2,
NULL AS o3, NULL AS id3,
category_level.*
FROM node AS top_level
INNER JOIN node AS category_level ON category_level.parentId = top_level.id
WHERE top_level.parentId = 0
)UNION ALL(
SELECT 3 AS lvl,
top_level.description AS o1, top_level.id AS id1,
category_level.description AS o2, category_level.id AS id2,
last_level.description AS o3, last_level.id AS id3,
last_level.*
FROM node AS top_level
INNER JOIN node AS category_level ON category_level.parentId = top_level.id
INNER JOIN node AS last_level ON last_level.parentId = category_level.id
WHERE top_level.parentId = 0
)
ORDER BY o1,o2,o3;
I added a lvl field to the selects, different value for each level. Also added o1,o2,o3 for ordering nested levels nicely, of course you may have another needs. You could process all rows in PHP, for example split them into 3 arrays (one for each level), or maybe create a lookup table by id, etc.
It might be worth doing this in PHP, as opposed to SQL if you're working with an external database. I haven't benchmarked the following, so try with your data and see if performance is problematic or not.
You can choose yourself what to do with orphaned records (which reference parentIDs that don't exist anymore).
Ordering in PHP like this requires that you have all of your data beforehand, so use something like PDO's fetchAll(PDO::FETCH_ASSOC) method, which should result in something like this:
$data_from_database = array(
array("id" => 1, "parentId" => 0, "description" => "Level 1"),
array("id" => 2, "parentId" => 1, "description" => "Level 1a"),
array("id" => 3, "parentId" => 1, "description" => "Level 1b"),
array("id" => 4, "parentId" => 0, "description" => "Level 2"),
array("id" => 5, "parentId" => 2, "description" => "Level 1a1"),
array("id" => 6, "parentId" => 5, "description" => "Level 1a11a"),
array("id" => 7, "parentId" => 5, "description" => "Level 1a11b"),
array("id" => 8, "parentId" => 9, "description" => "Level 3"),
);
First off, you'll want to have the primary key (ID) as the array's keys. The following also adds the keys "children" and "is_orphan" to every record.
$data_by_id = array();
foreach($data_from_database as $row)
$data_by_id[$row["id"]] = $row + array(
"children" => array(),
"is_orphan" => false
);
This will look something like this:
$data_from_database = array(
1 => array("id" => 1, "parentId" => 0, "description" => "Level 1",
"children" => array(), "is_orphan" => false),
...
);
Now, it gets tricky: we'll loop through the array and add references.
foreach($data_by_id as &$row)
{
if($row["parentId"] > 0)
{
if(isset($data_by_id[$row["parentId"]]))
$data_by_id[$row["parentId"]]["children"][] = &$row;
else
$row["is_orphan"] = true;
}
}
unset($row); // Clear reference (important).
The last step is to clean up the 'root' of the array. It'll contain references to duplicate rows.
foreach($data_by_id as $id => $row)
{
// If you use this option, you'll remove
// orphaned records.
#if($row["parentId"] > 0)
# unset($data_by_id[$id]);
// Use this to keep orphans:
if($row["parentId"] > 0 AND !$row["is_orphan"])
unset($data_by_id[$id]);
}
Use print_r($data_by_id) after every step to see what happens.
If this proves to be a time consuming operation, try to build up the tree by only doing SELECT id, parentId FROM ... and then later fetching the metadata such as description. You could also store the result in Memcache or serialized into a database.
i also had the same kind of problem but after lot of googling and stackoverflowing :-)
i found my answer....
Here is my way of coding.
function showComments($parent = 0)
{
$commentQuery = "SELECT * FROM comment WHERE parent = ".mysql_real_escape_string($parentId);
$commentResult = mysql_query($commentQuery)
while ($row = mysql_fetch_array($commentResult))
{
echo '[Table containing comment data]';
showComments($row['commentID']);
}
}
showComments();