Adding dynamic array to the end of a static array PHP - php

I've got the following code which is within a sql loop to determine how many rows i output onto a spreadsheet. Basically without pasting the full thing as it's quite a lengthy statement, the top SQL statement will return 60 rows, which will contain the variables I enter into the original $data1 array.
$stmt2= $mysqV1->prepare("SELECT DISTINCT master_recipe, recipe, matl_id, comp_length, comp_width, comp_tck from components where recipe > 0 and matl_id > 0 order BY CAST(recipe AS UNSIGNED) ASC" );
foreach ($result2 as $key2=>$value2)
{
$data1[]=(array("Master Recipe"=>$master_recipe,"Recipe"=>$recipe,"Recipe Name"=>$recipe_name,"Material"=>$material,"Length"=>$comp_length,"Width"=>$comp_width,"Thickness"=>$comp_tck));
}
I then have a further nested loop (inside the original $result2 loop) which will determine how many elements i add to that array, as the value will change from record to record. I have tried to declare an array then use array push and array merge but neither of them seem to do what i want.
$temp7 = array($master_recipe);
$stmt7= $mysqV1->prepare("Select * from machine where master_recipe = ? order by route_header_id asc" );
$stmt7->execute($temp7);
$result7=$stmt7->fetchAll();
foreach ($result7 as $key7=>$value7)
{
$station_id = $value7['route_header_id'];
$time_taken = $value7['time_hrs'];
$a[] = (array("StationID"=>$time_taken));
array_push($data1,$a);
}
So what I would like this to do is add the contents of $a to the end of $data1 to give me 1 array value which then prints out to my spreadsheet(the print part is already working for the $data1 array) but it's not adding the $a to it.
Final result I would like to end up something like this for the value in $data1
$data1[]=(array("Master Recipe"=>$master_recipe,"Recipe"=>$recipe,"Recipe Name"=>$recipe_name,"Material"=>$material,"Length"=>$comp_length,"Width"=>$comp_width,"Thickness"=>$comp_tck,"$station_id1"=>$time_taken,"$station_id2"=>$time_taken2,"$station_id3"=>$time_taken3));

Put the row that you're adding to $data1 in the $a variable, then you can add new elements to that row before you push it into $data1.
foreach ($result2 as $value2) {
$master_recipe = $value2['master_recipe'];
$recipe = $value2['recipe'];
...
$a = array("Master Recipe"=>$master_recipe,"Recipe"=>$recipe,"Recipe Name"=>$recipe_name,"Material"=>$material,"Length"=>$comp_length,"Width"=>$comp_width,"Thickness"=>$comp_tck);
$temp7 = array($master_recipe);
$stmt7= $mysqV1->prepare("Select route_header_id, time_hrs from machine where master_recipe = ? order by route_header_id asc" );
$stmt7->execute($temp7);
while ($value7 = $stmt7->fetch())
{
$station_id = $value7['route_header_id'];
$time_taken = $value7['time_hrs'];
$a[$station_id] = $time_taken;
}
$data1[] = $a;
}

What if you change your initial set of $data1 to this:
$data1= array(
"Master Recipe"=>$master_recipe,
"Recipe"=>$recipe,
"Recipe Nme"=>$recipe_name,
"Material"=>$material,
"Length"=>$comp_length,
"Width"=>$comp_width,
"Thickness"=>$comp_tck
);
then, in your loop..
foreach ($result7 as $key7=>$value7)
{
$station_id = $value7['route_header_id'];
$time_taken = $value7['time_hrs'];
$data1[$station_id] = $time_taken;
}

Related

How do I place in order 3,4 and 5 values based on amount (high-low) php

I started writing this code to determine which value within 3 date of births was the highest. As I got to as far as you can see I realised this was a silly way of doing it. There will at times be 4 values or even 5 values so writing every combination like this is sloppy.
$new_date_year1 etc are pre defined from a html form.
Can someone recommend another way of doing this.
$valuename1 = "Tom";
$valuename2 = "Jack";
$valuename3 = "Fred";
if ($amount == "3") {
if ($new_date_year1 > $new_date_year2 and $new_date_year1 > $new_date_year3 and $new_date_year2 > $new_date_year3) {
$highest_amount = $valuename1;
$second_amount = $valuename2;
$third_amount = $valuename3;
}
else if ($new_date_year1 > $new_date_year2 and $new_date_year1 > $new_date_year3 and $new_date_year3 > $new_date_year2) {
$highest_amount = $valuename1;
$second_amount = $valuename3;
$third_amount = $valuename2;
}
}
Thanks is advance for any help
just in html form replace variable names from $new_date_year1 into $new_date_year[] etc.
then in php You will have array that is sortable, so:
$new_date_year[] = '2015';
$new_date_year[] = '2018';
$new_date_year[] = '2016';
You can insert data to the array in this way as well(using array_push):
// implementing an empty array.
$new_date_year = [];
//using array_push
//you can pass multiple values to the array for explain it further i will pass '2015','2016','2018' to the array.
array_push($new_date_year,'2015','2016','2018');
After adding the values to the array you can sort the array using rsort which ,
sorts an array in reverse order (highest to lowest).
rsort($new_date_year);
$highest_amount = $new_date_year[0];
$second_amount = $new_date_year[1];
$third_amount = $new_date_year[2];

Check if multiple dates are the same in foreach

I have an "Events" table in MySQL :
EventsDate('id','event','start_date','end_date')
I'd like to check if multiple events have the same start date to show it differently in my HTML template.
My SQL request is :
SELECT * FROM EVENTSDATE where event='$id' and start_date>='$today' order by start_date asc
Now my foreach :
foreach ($upcomingDates as $value) { //$upcoming is the array with my sql request
}
How can I say : "if you find two rows with the same start_date, echo something"
I have a slightly different approach.
// Array to contain all values
$container = array();
// Loop through your existing array
foreach ($upcomingDates as $key => $value) {
// Check if the value is already in the container array
// If this is the case, its a duplicate.
if (array_key_exists($value['start_date'], $container)) {
$container[$value['start_date']]++;
echo $value.' is a duplicate with key '.$key;
}
// Add each value to the array
$container[$value['start_date']] = 1;
}
Another method is to use array_count_values()
foreach(array_count_values($upcomingDates) as $value => $c) {
if ($c > 1) {
echo $value.' is a duplicate';
}
}
Note that the second option won't work if your $upcomingDates is an array of arrays.
You can make an empty array before the for loop, and add each value in as a key. Then, on each iteration you can check that array for the key, like so:
$values = [];
foreach ($upcomingDates as $value) { //$upcoming is the array with my sql request
if(isset($values[$value])) //duplicate value found
//do something here
$values[$value] = 1;
}
Since you're ordering your events by start_date:
for ($i = 0, $length = count($upcomingDates); $i < $length; $i++) {
$date = $upcomingDates[$i];
if (isset($upcomingDates[$i + 1]) &&
$upcomingDates[$i + 1]['start_date'] == $date['state_date']) {
echo 'this and the next date are equal';
}
}
Try out GROUP BY
look here: GROUP BY
if you want to find duplicates, then you can directly get it from database
ex.
SELECT * FROM EVENTSDATE where event='$id' and start_date>='$today' GROUP BY start_date having count(start_date) > 1 order by start_date asc
or you can find duplicates from resulting array
return only duplicated entries from an array

php recursive search and count of a value in json

I have a json feed with 6 objects all which have objects inside of them. I have an ID of something I am trying to search and count in another object.
if (isset($_GET['steamusr'])) {
$user = $_GET['steamusr'];
$myinv = 'http://steamcommunity.com/id/'.$user.'/inventory/json/295110/1/';
$content2 = file_get_contents($myinv);
$json2 = json_decode($content2, true);
$imgurlbase = 'http://steamcommunity-a.akamaihd.net/economy/image/';
foreach($json2['rgDescriptions'] as $i){
$item = $i['market_name'];
$icon = $i['icon_url'];
$fetchdata = 'http://steamcommunity.com/market/priceoverview/?appid=295110&currency=1&market_hash_name=' . urlencode($item);
$grab = file_get_contents($fetchdata);
$id = json_decode($grab, true);
$itemid = $i['classid'];
foreach($json2->rgInventory as $i2){
if($i2->$itemid == $itemid){
$ci = 0;
$count = $ci++ ;
}
}
All the data comes from rgDescriptions first, then rgInventory has the number of objects to count within it. The item ID comes from $itemid which I then need to search rgInventory for and then count the amount of matching id's in there from the set value $itemid.
My biggest issue is rgInventory has unique objects so I am trying to do a recursive/wildcard search of matching classid's.
The json structure can be found here: http://www.jsoneditoronline.org/?url=http://steamcommunity.com/id/fuigus/inventory/json/295110/1/
I think your code is correct in essence but you're not comparing the right things.
$json = json_decode($content2);
foreach ($json["rgDescriptions"] as $item) {
$num = 0;
foreach ($json["rgInventory"] as $inventory_entry) {
if ($inventory_entry["classid"] === $item["classid"]) {
$num += 1;
}
}
// do something with $num
var_dump($item["classid"] . ": " . $num);
}
The line:
if($i2->$itemid == $itemid){
Is bad, $i2->$itemid resolves to $i2->1107865473 which doesn't exist. I think you intended $i2->classid.
Error like this happen because you're using meaningless, abstract variable names. $i, $i2 and $content2, these are meaningless. You're also mixing the terms itemid and classid, it's easy to get confused.
Also, you're mixing bracket notation and object notation. Pick one and stick to it.

array/other data structure to store data in 2 dimention

Here First of all I fetched all tags from database. (tags are string like marketting,jobs etc).
$POS is array of POS(parts of speech words). For each words in this array, for given tag, I am calculating probability using writtten equation.
As it is appearing, two nested loops are there. To make decision, I need highest value from array $prob and tag belonging to that value.
Here in this code I will get all values in array $prob and from that I can get highest value, but how can I persist tag value too? is there any other data strcture in PHP to manage this short of scenario?
$selectTag = mysqli_query($con,"SELECT tag from koove_tag");
$prob = array();
$i=0;
while ($row1 = #mysqli_fetch_array($selectTag))
{
foreach($POS as $p)
{
//Calculate total pos for given tag
$selectPOS = mysqli_query($con,"SELECT * from koove_post where tag = '".$row1[tag]."'");
while ($row2 = #mysqli_fetch_array($selectTag))
{
$totalPOSs.=$row2[pos].",";
}
$totalPOS_count = str_word_count($totalPOSs);
//calculate how many times particular 'pos' appears for given tag
$selectPOS = mysqli_query($con,"SELECT * from koove_post where tag = '".$row1[tag]."'");
while ($row3 = #mysqli_fetch_array($selectTag))
{
$POSs.=$row3[pos].",";
}
$pos_Count = echo substr_count($string, $p);
//calculate distinct POS in all POSs for all tags
$selectPOS = mysqli_query($con,"SELECT pos from koove_post");
while ($row4 = #mysqli_fetch_array($selectTag))
{
$POSs.=$row4[pos].",";
}
$distinct_pos_Count = echo substr_count($string, $p);
$prob[$i] = ($pos_Count + 1)/ ($totalPOS_count + $distinct_pos_Count);
$i++;
}
}
There are large numbers(thousands) of posts, if is there any better approach to faster the processing that also welcome.
Certainly. Use the stdClass() object to hold the values that you need. Then write method to sort them. For example:
$prbo[$i] = new stdClass();
$prob[$i]->value = ($pos_Count + 1)/ ($totalPOS_count + $distinct_pos_Count);
$prob[$i]->tag = $row1[tag];
After you build that array, then write a custom sort function.
http://www.php.net/manual/en/array.sorting.php
1.You can use join query that will eliminate one of cycles.
2.You can get highest value with end(array) , or custom sort function.

Multi-dimension array value sorting in PHP

I am building up an array with a set of database fields with information about table, actual field name and descriptive field name as a multi-dimensional array. Here is what it currently looks like:
$Fields['User']['ID'] = "User ID";
$Fields['User']['FirstName'] = "First Name";
$Fields['Stats']['FavouriteOrder'] = "Favourite Item Ordered";
$Fields['Geographic']['Location'] = "Current Location";
$Fields['Geographic']['LocationCode'] = "Current Location Code";
Okay, this is fine, but I am piping this into a system that allows exporting of selected fields, and in the end I want to foreach() through the different levels, extract the data and then ultimately have all the descriptive fields to be displayed sorted alphabetically using their descriptive name. So ultimately in the order: Current Location, Current Location Code, Favorite Item Ordered, First Name then User ID - obviously keeping index associations.
I can't use usort() and I can't use array_multisort()... or maybe I can and I just don't know how. usort() seems to need a key to sort by, but I have variable keys. array_multisort() just seems to do the same as sort() really.
This is for a 2D array only. Not the most elegant piece of code I've written, but it works...
foreach($Fields as $key=>$var) {
ksort($var);
$Fields[$key]=$var;
}
ksort($Fields);
Let me rather give a real-life data example, as opposed to fake data because the fake data nearly confused me. So, fake data is commented.
/*
$Fields['User']['ID'] = "User ID";
$Fields['User']['FirstName'] = "First Name";
$Fields['Stats']['FavouriteOrder'] = "Favourite Item Ordered";
$Fields['Geographic']['Location'] = "Current Location";
$Fields['Geographic']['LocationCode'] = "Current Location Code";
*/
$Fields['Product']['ReferenceNumber'] = "Product Reference Number";
$Fields['Product']['Halaal'] = "Halaal Status";
$Fields['Product']['Kosher'] = "Kosher Status";
$Fields['Product']['KosherType'] = "Kosher Type";
$Fields['Product']['CuringSalts'] = "Curing Salts Status";
$Fields['Product']['ProductVisibility'] = "Product Visibility";
$Fields['Product']['ProductStatus'] = "Product Status";
$Fields['Product']['PackBarCode'] = "Barcode";
$Fields['Product']['ProductDescription'] = "Product Description";
$Fields['Pack']['PackSize'] = "Pack Size";
$Fields['Pack']['PackSizeNumeric'] = "Numeric Pack Size";
$Fields['Allergens']['ContainsNuts'] = "Product Contains Nuts";
foreach ($Fields as $key => $value) {
ksort($value);
$Fields[$key] = $value;
}
ksort($Fields);
I'm having one of 'those' Fridays... print_r($Fields) reveals that the keys are being sorted and values are associated, but it's still sorting by the keys and not the end value.
It's almost like i need a reverse sorting system which checks all values first, sorts them and then says 'okay where do you belong ... ah you belong to FieldX in Table Y'
I was hoping there was a sneaky clever way to do it, perhaps there is, but I guess I'll write a function to parse through the data, write a reversed array and then re-write the original in value-order. Hectically inefficient, but it'll do.
Still open to better suggestions though!
I literally had to work this out yesterday for a project I was working on - here's my code:
Resource array looks like this:
$resource[$count]['title']
$resource[$count]['filepath']
$resource[$count]['filename']
$resource[$count]['taxonomy'][0]
A couple of sort functions to sort by title ASC or DESC
function compare_asc($a, $b) {
return strcmp($a['title'], $b['title']);
}
function compare_desc($a, $b) {
if ($a['title'] == $b['title']) {
return 0;
}
return ($a['title'] > $b['title']) ? -1 : 1;
//return strcmp($a['title'], $b['title']);
}
And finally use usort to do the dirty before you loop through $resource and output whatever it is you need.
usort($resource, "compare_asc");
Okay, it's not elegant at all. So I don't encourage using this and will look for a better way down the line. But here's the solution I've got that works with the examples above and below.
Unfortunately, the way I want it to be, the array HAS to contain a preceding 'ordering' number so, I suppose it's a fail on my part from the very beginning. But it works now.
$TempDescArray = array();
$TempFieldArray = array();
$TempTableArray = array();
$Pointer = 0;
foreach ($Fields as $Table => $FieldsArray) {
foreach ($FieldsArray as $Field => $Description) {
$TempDescArray[$Pointer] = $Description;
$TempFieldArray[$Pointer] = $Field;
$TempTableArray[$Pointer] = $Table;
$Pointer++;
}
}
asort($TempDescArray);
$Fields = array();
$Pointer2 = 0;
foreach ($TempDescArray as $Pointer => $Description) {
$Fields[$Pointer2][$TempTableArray[$Pointer]][$TempFieldArray[$Pointer]] = $Description;
$Pointer2++;
}

Categories