I have a php script creating a multidimensional array:
$res = mysql_query("SELECT `date`, `temperature` FROM `general` ORDER BY `date`", $db);
$outside_temperature_array = array();
while($row = mysql_fetch_assoc($res)) {
$date = $row['date'];
$temperature = $row['temperature'];
$temp_array = array();
array_push($temp_array, $date);
array_push($temp_array, $temperature);
array_push($outside_temperature_array, $temp_array);
unset($temp_array);
}
print_r($outside_temperature_array);
The multidimensional array looks like this. It has a unix timestamp in sequential order along with a value.
Array
(
[0] => Array
(
[0] => 1452483001
[1] => 40
)
[1] => Array
(
[0] => 1452483301
[1] => 39
)
[2] => Array
(
[0] => 1452483600
[1] => 39
)
[3] => Array
(
[0] => 1452483901
[1] => 39
)
[4] => Array
(
[0] => 1452484201
[1] => 39
)
[5] => Array
(
[0] => 1452484502
[1] => 39
)
[6] => Array
(
[0] => 1452484801
[1] => 38
)
[7] => Array
(
[0] => 1452485101
[1] => 38
)
[8] => Array
(
[0] => 1452485400
[1] => 38
)
[9] => Array
(
[0] => 1452485701
[1] => 39
)
[10] => Array
(
[0] => 1452486002
[1] => 39
)
)
I want to omit all identical values except for the first and last, only when they show up sequentially. Think of this plotted on a line graph. I basically want to remove the unnecessary values that fall between two points of identical values. So the above array would change to this:
Array
(
[0] => Array
(
[0] => 1452483001
[1] => 40
)
[1] => Array
(
[0] => 1452483301
[1] => 39
)
[2] => Array
(
[0] => 1452484502
[1] => 39
)
[3] => Array
(
[0] => 1452484801
[1] => 38
)
[4] => Array
(
[0] => 1452485400
[1] => 38
)
[5] => Array
(
[0] => 1452485701
[1] => 39
)
[6] => Array
(
[0] => 1452486002
[1] => 39
)
)
You need to:
Keep track of the last temperature.
When a temperature change is detected, append the held row (if applicable) and the current row to the final array.
If there was no temperature change, hold the row as the last duplicate.
After the loop, append the held row to the final array if it is set.
This should work for you.
<?php
$res = mysql_query("SELECT `date`, `temperature` FROM `general` ORDER BY `date`", $db);
$outside_temperature_array = array();
$last_temp = null;
$held_row = null;
while($row = mysql_fetch_assoc($res)) {
// If we're on a new temperature
if ($row['temperature'] !== $last_temp) {
// Append and clear the held row first
if (is_array($held_row)) {
$outside_temperature_array[] = [$held_row['date'], $held_row['temperature']];
$held_row = null;
}
// Append this row and note the temperature
$outside_temperature_array[] = array($row['date'], $row['temperature']);
$last_temp = $row['temperature'];
} else {
// Hold the row in case the next row is different
$held_row = $row;
}
}
// If the last row was not appended to the array
if (is_array($held_row)) {
// Append the held row
$outside_temperature_array[] = array($held_row['date'], $held_row['temperature']);
}
print_r($outside_temperature_array);
$res = mysql_query("SELECT `date`, `temperature` FROM `general` ORDER BY `date`", $db);
$outside_temperature_array = array();
$oldTemperature = null;
while($row = mysql_fetch_assoc($res)) {
if($oldTemperature == $row['temperature'] && next($row)['temperature'] == $oldTemperature )
continue;
}
$oldTemperature = $row['temperature'];
$outside_temperature_array[] = array($row['date'],$row['temperature']);
}
print_r($outside_temperature_array);
You can try passed eqvivalent element in array use continue, but this code non testing. I think maybe you can execute sql query for this. And mysql this old extensions you need use PDO or Mysqli.
Related
In my PHP file, I'm receiving a total of 4 variables $data, $date, $shift and $val1.
$data is an array and the other 3 are date and 2 strings obtained through AJAX with no problem.
What I'm trying to do is to insert these 3 values inside my $data variable.
I tried using array merge, and a For each loop with multiple instances but no luck so far.
I obtained my variables like this:
if (isset($_POST['date'])){
$date = $_POST['date'];
$date = json_encode($date);
$date = json_decode($date);
}
if (isset($_POST['shift'])){
$shift = $_POST['shift'];
$shift = json_encode($shift);
$shift = json_decode($shift);
}
if (isset($_POST['val1'])){
$val1 = $_POST['val1'];
$val1 = json_encode($val1);
$val1 = json_decode($val1);
}
if (isset($_POST['data'])){
$dat = $_POST['data'];
$data = json_decode($dat, true);
}
$values = array($date,$shift,$val1);
$r = (array_merge($data, $values));
My data array looks something like this:
Array (
[0] => Array (
[data] => Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => Mat1
[5] => Box1
[6] => 100
[7] => 100
[8] => Piece1
[9] => Loc1
[10] => Mach1
[11] => 1000
[12] => Accepted
)
)
)
[1] => 2019-04-09
[2] => First
[3] => Value1
)
But what I want to achieve is this:
Array (
[0] => Array (
[data] => Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => Mat1
[5] => Box1
[6] => 100
[7] => 100
[8] => Piece 1
[9] => Suc1
[10] => Mach1
[11] => 1000
[12] => Accepted
[13] => 2019-04-09
[14] => First
[15] => Value1
)
)
)
)
What am I doing wrong? Or How can I achieve what I'm trying to do?
Edit: Since I can get more than one array at my array, something like this
Array (
[0] => Array (
[data] => Array (
[0] => Array (...)
[1] => Array (...)
[2] => Array (...)
[3] => Array (...)
)
)
)
I just added this code to #HelgeB answer, I'm leaving it here in case someone might need it in the future.
$count = count($data[0]['data']);
for ($i=0; $i < $count ; $i++) {
$data[0]['data'][$i][] = $date;
$data[0]['data'][$i][] = $shift;
$data[0]['data'][$i][] = $val1;
}
As far as I can see from your merged output, your $data array structure is $data[0]['data'][0] = [1,2,3,...,'Accepted'].
So in my opinion you need to insert the values exactly on the level $data[0]['data'][0] to obtain your result.
The simplest way to achieve this would be:
$data[0]['data'][0][] = $date;
$data[0]['data'][0][] = $shift;
$data[0]['data'][0][] = $val1;
If you want to use your merge approach you need to merge on the correct level like this:
$r = [0 => ['data' => [0 => (array_merge($data[0]['data'][0], $values))]]];
I have the database and i want to create a matrix or probably 2d array in PHP where the first column comes from first query and then i loop again another query. I am getting it but when it comes to the matrix i want first column populate from the first column and the rest of the column in that row should populate depending on the data for that particular query. you might better understand after looking at the code
<!DOCTYPE html>
<html>
<?php
require ('connect.php');
$pro_name = $_POST['project'];
$sheet_type = $_POST['sheet_set'];
echo $pro_name ."-";
echo $sheet_type . "<br/>";
?>
<?php
$doc_num_data = array();
$qry_doc_num = "SELECT DISTINCT document_number FROM `$pro_name`.Instruments";
$result_doc_num = mysqli_query($connection, $qry_doc_num) or die(mysqli_error($connection));
while($doc_num = mysqli_fetch_row($result_doc_num)){
if($doc_num[0] != ''){
$qry_ins = "SELECT CONCAT(tag_letters,'-',tag_numbers) FROM `$pro_name`.Instruments WHERE document_number = '$doc_num[0]'";
$result_qry_ins = mysqli_query($connection, $qry_ins) or die(mysqli_error($connection));
// array_push($doc_num_data, $doc_num);
// $doc_num_data = array();
while($ins_doc = mysqli_fetch_row($result_qry_ins)){
$instruments_tag = $ins_doc[0];
array_push($doc_num_data, $doc_num);
}
}
}
echo "<pre>";
print_r($doc_num_data);
echo "</pre>";
?>
</html>
I want something like this
[doc1] [ins1] [ins2] []
[doc2] [ins1] [] []
[doc3] [ins1] [ins2] [ins3]
[doc4] [ins1] [ins2] []
thats the result what i get basically each element is saving in different array
Array (
[0] => Array
(
[0] => test1
)
[1] => Array
(
[0] => PIT-100
)
[2] => Array
(
[0] => test1
)
[3] => Array
(
[0] => PIT-330
)
[4] => Array
(
[0] => PIT-330
)
[5] => Array
(
[0] => PIT-330
)
[6] => Array
(
[0] => test2
)
[7] => Array
(
[0] => PIT-300
)
[8] => Array
(
[0] => PIT-300
)
[9] => Array
(
[0] => PIT-300
)
[10] => Array
(
[0] => PIT-300
)
[11] => Array
(
[0] => PIT-300
)
The problem you're having is with array_push(). All that is going to do (as you can see) is stack the values into a LIST, not a hash / multi-dimensional array.
What you want is a list of things that are referenced by that doc ID, right?
Try this:
if($instruments_tag != null) array_push($doc_num_data[$doc_num], $instruments_tag);
I think that is what you're looking for, or close to it at any rate, and it won't add that empty value at the end. If you want that, remove the if.
Array
(
[0] => Array
(
[0] => test1
[1] => PIT-100
[2] => PIT-330
)
[1] => Array
(
[0] => test2
[1] => PIT-300
)
[2] => Array
(
[0] => test3
[1] => TIT-100
)
[3] => Array
(
[0] => test5
[1] => TIT-200
[2] => TIT-900
[3] => PIT-000
)
[4] => Array
(
[0] => test4
[1] => TIT-1000
)
[5] => Array
(
[0] => test6
[1] => TIT-999
)
)
using this code
<?php
$doc_num_data = array();
$qry_doc_num = "SELECT DISTINCT document_number FROM `$pro_name`.Instruments";
$result_doc_num = mysqli_query($connection, $qry_doc_num) or die(mysqli_error($connection));
$i=0;
while($doc_num = mysqli_fetch_row($result_doc_num)){
$j=1;
if($doc_num[0] != ''){
$qry_ins = "SELECT CONCAT(tag_letters,'-',tag_numbers) FROM `$pro_name`.Instruments WHERE document_number = '$doc_num[0]'";
$result_qry_ins = mysqli_query($connection, $qry_ins) or die(mysqli_error($connection));
//echo $doc_num[0];
$doc_num_data[$i][0] = $doc_num[0];
//echo $doc_num_data[$i];
// $doc_num_data = array();
while($ins_doc = mysqli_fetch_row($result_qry_ins)){
$instruments_tag = $ins_doc[0];
$doc_num_data[$i][$j]= $instruments_tag;
$j=$j+1;
}
}
$i= $i+1;
}
I want to sort my array according to idai value. I've tried to use SORT,KSORT,USORT but nothing useful.
Here is my data
Array
(
[0] => Array
(
[0] => Array
(
[idai] => 4
[id] => 6187
[name] => xyz
)
[1] => Array
(
[idai] => 5
[id] => 5256
[name] => abc
)
[2] => Array
(
[idai] => 10
[id] => 21921
[name] => qwe
)
[3] => Array
(
[idai] => 6
[id] => 29679
[name] => IOU
)
[4] => Array
(
[idai] => 11
[id] => 21062
[name] => STU
)
)
)
And I'm not sure why I'm getting this nested array..
Here is my how I declared my array:
$return_arr = array();
$return_arr['feed'] = array();
My code to store data in array from my db
$query = "SELECT * FROM user_post WHERE userid = '$friend_id'";
$result = mysql_query($query);
while( $row = mysql_fetch_array($result) ) {
$row_array['idai'] = $row['id'];
$row_array['id'] = $row['post_id'];
$row_array['name'] = $pic['name'];
array_push($return_arr['feed'],$row_array);
}
Try this code:
$return_arr['feed'][$row['id']] = $row_array;
or if you want not nested array:
$return_arr[$row['id']] = $row_array;
it will automaticly sort as array key is id
suppose I have an array like this :
Array
(
[0] => Array
(
[0] => A
[1] => 20
)
[1] => Array
(
[0] => B
[1] => 10
)
[2] => Array
(
[0] => G
[1] => 5
)
[3] => Array
(
[0] => A
[1] => 15
)
)
I would like to remove duplicate values and sum just a row of array :
What I want :
Array
(
[0] => Array
(
[0] => A
[1] => 35 // <= sum : 20 + 15
)
[1] => Array
(
[0] => B
[1] => 10
)
[2] => Array
(
[0] => G
[1] => 5
)
)
I've read this question before.
updated
while($row = $stmt->fetch()){
$arr = array(
'GoodMainCode'=>persian_sql_to_php($row['GoodMainCode']), // <= like A in the example
'title'=> persian_sql_to_php($row['GoodName']),
'author'=>persian_sql_to_php($row['moalef']),
'publisher'=>persian_sql_to_php($row['Nasher']),
'translator'=>persian_sql_to_php($row['Motarjem']),
'price'=>persian_sql_to_php($row['SellPrice1']),
'isbn'=>persian_sql_to_php($row['ISBN']),
'amount'=>persian_sql_to_php($row['Amount']), // <= if GoodMainCode is same key, I must sum it.
'year_of_publish'=>persian_sql_to_php($row['SaleChap']),
'period_print'=>persian_sql_to_php($row['NobateChap'])
);
array_push($mjson,$arr);
}
//added
foreach($mjson as $v){
if(!isset($result[$v['GoodMainCode']]))
$result[$v['GoodMainCode']] = $v;
else
$result[$v['GoodMainCode']]['amount'] += $v['amount'];
}
This should work for you:
Just loop through your array and check if in your $result array is a key with the letter of the current inner Array from $arr. If not add it to the $result array and initialize the second key with the number.
If there is already a key with this letter you can simply add the numbers together in this array. At the end I simply use array_values() to reindex the entire array.
<?php
foreach($arr as $v) {
if(!isset($result[$v[0]]))
$result[$v[0]] = $v;
else
$result[$v[0]][1] += $v[1];
}
$result = array_values($result);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[0] => A
[1] => 35
)
//...
[2] => Array
(
[0] => G
[1] => 5
)
)
Hell once again, I am wondering how do you go about adding data to a new array index when inside a foreach loop?
the code I have atm is,
// Connect to the database to gather all data pertaiing to the link in question
$assoResult = mysql_query("SELECT * FROM associate_users");
while ($assoRow = mysql_fetch_field($assoResult)) {
$resultArray[] = $assoRow->name;
}
// Connect to the database to gather all data pertaiing to the link in question
$assoResult2 = mysql_query("SELECT * FROM associate_users WHERE id='$getID'");
while ($assoRow2 = mysql_fetch_object($assoResult2)) {
foreach ($resultArray as $row) {
$array = array(array( 1 => $assoRow2->$row, 2 => $row, ),);
echo "<br />"; print_r($array);
}
}
Below is the outputted data that comes from the "echo "br />"; print_r($array);" line.
=================================================================
Array ( [0] => Array ( [1] => 1 [2] => id ) )
Array ( [0] => Array ( [1] => Bob[2] => contactName ) )
Array ( [0] => Array ( [1] => Bob's Tyres [2] => company ) )
Array ( [0] => Array ( [1] => XXXXXXXXXXXXXX [2] => address1 ) )
Array ( [0] => Array ( [1] => XXXXXXXXXXXXXX [2] => address2 ) )
Array ( [0] => Array ( [1] => XXXXXXXXX [2] => address3 ) )
Array ( [0] => Array ( [1] => XXXXXX [2] => postcode ) )
As you can see the array is being created a new over and over, what I need is for the above data to increment the 1st dimension index key on every loop, so it looks like...
=================================================================
Array ( [0] => Array ( [1] => 1 [2] => id ) )
Array ( [1] => Array ( [1] => Bob[2] => contactName ) )
Array ( [2] => Array ( [1] => Bob's Tyres [2] => company ) )
Array ( [3] => Array ( [1] => XXXXXXXXXXXXXX [2] => address1 ) )
Array ( [4] => Array ( [1] => XXXXXXXXXXXXXX [2] => address2 ) )
Array ( [5] => Array ( [1] => XXXXXXXXX [2] => address3 ) )
Array ( [6] => Array ( [1] => XXXXXX [2] => postcode ) )
Thank you in advance I am out of all options in getting this to work and desperate.
Dan.
Change the values assigning part of your code to
$count=0;
foreach ($resultArray as $row) {
$array[$count][1] = $assoRow2->$row
$array[$count][2]=$row;
$count++;
echo "<br />"; print_r($array);
}
This code gets you the output you asked for without inefficiently using two queries:
// Connect to the database to gather all data pertaining to the link in question
$result = mysql_query("SELECT * FROM associate_users WHERE id=" . (int)$getID);
$resultArray = array();
$resultCount = 0;
$row = mysql_fetch_assoc($result);
$count = 0;
foreach ($row as $key => $value) {
$temp = array();
$temp[$count] = array(1 => $value, 2 => $key);
$count++;
echo "<br />"; print_r($temp);
}
Why you want it like this, I have no idea.
//extra code.declaring array
$array = array();
while ($assoRow2 = mysql_fetch_object($assoResult2)) {
foreach ($resultArray as $row) {
// 1st parameter is the array name, here array name is array .give gd name according to use
array_push($array,array( 1 => $assoRow2->$row, 2 => $row, ));
echo "<br />"; print_r($array);
}
}