How to merge sub-arrays based on first value php - php

I have an array that is put together. It's basically 24 data points across 7 stations. Each station has a data point each hour and a new sub0array is created for each data point. The problem with this, is I now want to split the data up based on station so I can sort it. When I go to do that array_filter doesn't work for me. I wanted to basically combine all of the values that have the same row 0 result in each sub-array. but keep each data point based on them. Row 0 is the station name. Here is an example of what the array looks like. There are 160 sub arrays. All I need to do is combine them together based on Station name. I was going to do this based on Array value, but the problem is if a data-point is missing, it breaks that logic.
Array
(
[0] => Array
(
[0] => STATIONONE
[1] => 02/22/15 04:00:00 PM
[2] => SW
[3] => Array
(
[0] => 4.51
)
[4] => MPH
[5] => Array
(
[0] => 16.1
)
[6] => MPH
)
[1] => Array
(
[0] => STATIONONE
[1] => 02/22/15 05:00:00 PM
[2] => S
[3] => Array
(
[0] => 2.7
)
[4] => MPH
[5] => Array
(
[0] => 9.61
)
[6] => MPH
)
And it just keeps repeating till I have 23 Values. Then the next station.
So 0-22 subarray value = station 1
23-45 subarray value = station 2
etc.. just stating to help show what I am trying to do.

It isn't entirely clear what you expect your output to be, but this might get you there:
$entriesByStation = []
foreach ($entries as $entry) {
$entriesByStation[$entry[0]] = $entry;
}
This will group all the the entries by station name in the $entriesByStation array

The accepted answer got me close into figuring this out. I had to do this by station though. So I just created 7 foreach statements and created an array for each station. This way I can also merge the array together if needed.
# Parse our All Data and set station
foreach ($array as $entry) {
if ($entry[0] === "STATIONONE"){
$S1pkwsite = ($entry[0]);
$S1pkwvalue = ($entry[5][0]);
$S1pkwdate = ($entry[1]);
$S1pkwunit = ($entry[6]);
$S1wspvalue = ($entry[3][0]);
$S1wspunit = ($entry[4]);
$S1wdrvalue = ($entry[2]);
$S1pkwdataarray[] = array('SiteName'=>$S1pkwsite,'DATE'=>$S1pkwdate,'WDR'=>$S1wdrvalue,'VALUE'=>$S1pkwvalue,'UNIT'=>$S1pkwunit);
}
}
array_push ($Stationone_data, $pkwdataarray);
$Stationone_data = array_shift($Stationone_data);

Related

PHP nested foreach is only taking first key

I am getting a lot of data from a form through POST. As an example, here is some of the data:
event_date:
Array (
[0] => 2017-04-02
[1] => 2017-04-02
[2] => 2017-04-03 )
equipment_name:
Array
(
[0] => Array
(
[0] => Mic
[1] => Sound System
[2] => Wireless Mic
[3] => Two Point Stage Wash
)
[1] => Array
(
[0] => Sound System
)
[2] => Array
(
[0] => Projection Package
[1] => Gobo
[2] => Audio Engineer
)
)
To save this data I am doing two foreach loops:
foreach ($_POST['event_date'] as $key => $date) {
echo "event number [".$key."]<br>";
//insert into table value $_POST['event_date'][$key]
foreach ($_POST['equipment_name'] as $ekey => $value) {
echo "equipment number [".$key."][".$ekey."]<br>";
//insert into table value $_POST['equipment_name'][$key][$ekey];
}
}
Unfortunately my result is the following:
event number [0]
equipment number [0][0]
equipment number [0][1]
equipment number [0][2]
event number [1]
equipment number [1][0]
equipment number [1][1]
equipment number [1][2]
event number [2]
equipment number [2][0]
equipment number [2][1]
equipment number [2][2]
As you can notice, the nested key ($ekey) equals the first key, not showing items over that number (eg: equipment number [0][3]), and saving nothing if the amount of equipment is lower than that number (eg: equipment number [1][1] and [1][2]).
Why the nested loop has this behavior? How could I solve this issue?
If I understood your question right, I think you want to access a particular nested array from $_POST['equipment_name'], yet you always access the outer array. This is a simple fix, change your second foreach to:
foreach ($_POST['equipment_name'][$key] as $ekey => $value) {
^^^^^^

Setting an array item's value as the parent array's key (PHP) [duplicate]

This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 7 months ago.
I have an array of array that looks like this:
Array
(
[0] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[1] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[2] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
I want to set the key of the parent array with the value of id, so the result array looks like this:
Array
(
[I100] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[I101] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[I245] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
If possible I'd like to avoid using an additional loop to go through the array and creating a new array to store each item with the proper key, as the array can have thousands of items.
Thanks in advanced!
Despite your caveat, a loop is the obvious solution:
$newArray = [];
foreach($oldArray as $item)
$newArray[$item['id']] = $item;
If the problem you have is not specifically with a loop, but rather creating a copy of the array is causes excessive memory consumption, then you can edit the array in place, with a for loop:
for($i=0; $i<count($oldArray); $i++){
$oldArray[$oldArray[$i]['id']] = $oldArray[$i];
unset($oldArray[$i]);
}
Note this works because the id elements are alphanumeric strings, if they where simple integars then the above code could overwrite sections.
The only other solution is to build the correct array in the 1st place, in a similar manner.
For example, using PDO::fetch instead of PDO::fetchAll:
//$newArray = $sth->fetchAll(PDO::FETCH_ASSOC);
$newArray = [];
while($row = $sth->fetch(PDO::FETCH_ASSOC))
$newArray[$row['id']] = $row;
You can't overwrite keys while iterating through an array "on the fly". So here is solution with array_map which produces an array with needed structure:
// assuming $arr is your initial array
$result = [];
array_map(function($a) use (&$result){
$result[$a['id']] = $a;
}, $arr);
// $result contains the needed array
You can add needed key during creation of this array.

PHP Split array in subarrays

Note, array_chunk is not my solution (It seems to me).
I have an array of about 150.000 elements
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
[1] => Array
(
[name] => Alessandro
[phone] => 392222
)
[2] => Array
(
[name] => Alex
[phone] => 3922
)
[3] => Array
(
[name] => Capa
[phone] => 392
)
)
And so on. I would split this array in several arrays, of (for example) 3.000 elements every one.
I saw array_chunk, but it returns a single array with several subarray.
I need several subarray to store them in a database and elaborate in future.
I'm getting crazy to write a snippet starting from that $temp and divide it into smaller array.
$size_chunks = 1;
$temp = array_chunk($recipients, $size_chunks);
foreach ($temp as $key=>$value)
{
if ($key<$size_chunks)
{
$to_store[] = $temp[$key];
}
//print_r($to_store);
// pseudo sql
// INSERT INTO table (sub_recipient) VALUES ($to_store);
$to_store = array();
}
So, every time that for loop end, reduce temp, store $to_store array and restart for others chunks.
Thank you very much.
PS in my example chunk==1 because starting array is small... ;)
With my example of chunk = 1, I need from starting array this 4 arrays:
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
)
Array
(
[0] => Array
(
[name] => Alessandro
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Alex
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Capa
[phone] => 392
)
)
Another explain
1 - With a starting array of 15.000 elements, and chunk of 3.000, I need in output (15.000 / 3.000) = 5 arrays. I will save them in database, so in DB I will have 5 rows (a row for every array).
2 - With a starting array of 4 elements, and chunk of 1, I need in output (4 / 1) = 4 arrays. I will save them in database, so in DB I will have 4 rows (a row for every array).
array_chunks() already does what you want, you just have to save it:
$chunks = array_chunk($array, $size_chunks);
foreach ($chunks as $chunk) {
// save $chunk to your database
}
$recipients = Array(
Array("fdbvfdb","dsacsdcds"),
Array("hrloo","dacdsc"),
Array("dcsdc","adcsd"),
Array("dcsdc","adcsd")
);
$total = count($recipients);//count 150.000 elements
$i=1;
for($i=0;$i<$total;$i++){
$O = array_slice($recipients,$i,1);
print_r($O);
//Your insert/Save code
}
you can use this code there is uses Array_Slice

show random values from array of array

Below is a array generated by a query builder.
$random_array = Array ( [0] => Array ( [text] => A great time was had by all! )
[1] => Array ( [text] => KILL SHOT )
[2] => Array ( [text] => How is it possible)
[3] => Array ( [text] => http://www.youtube.com/watch?v=KwGOZpbxU9g )
[4] => Array ( [text] => http://www.youtube.com/watch?v=KwGOZpbxU9g )
)
Currently i am doing like this to print the random value
print_r(array_rand($random_array,1));
This is printing the array key as 3 or 1 etc(random from above array).I want to print the value of the key and not the key.
e.g I want to print the random value like this "http://www.youtube.com/watch?v=KwGOZpbxU9g" or "A great time was had by all!" instead of 3 or 1 which is printing now.
Is it possible to do this.
You will have one more line of code as shown below:
$array_key = array_rand($random_array,1); //get the key
print_r( $random_array[$array_key] ); //use the key to print value
What about simply calling
$randNumber = rand(0,count($random_array))-1; //index in array starts with 0
print (string) $random_array[$randNumber];

PHP sort array using another array no keys

Hello i have an array in php
Array
(
[0] => red
[1] => blue
[2] => green
[3] => yellow
[4] => purple
[5] => white
)
and i want to sort it using that array
Array
(
[0] =>
[1] => 0
[2] => -1
[3] => -5
[4] => -5
[5] => 9
)
so i want the element with the greatest value on the second array to come first on the first array not its value from the second array but the element it self from the first array to move in the first position on the first array! The second bigger to the second place etc.. elements with the same value don't care me how they will be arranged!
the output i want to get is
Array
(
[0] => white
[1] => blue
[2] => green
[3] => yellow
[4] => purple
[5] => red
)
You can use array_multisort() :
$ar1 = array(/* your SO links */);
$ar2 = array(/* your numbers */);
array_multisort($ar2, SORT_DESC, $ar1);
Documentation here
Use array_multisort.
see http://www.php.net/manual/fr/function.array-multisort.php, follow the "Exemple #1 Trier plusieurs tableaux"
Cordially
Lets call your arrays are $dataArray, and $sortArray respectively
asort($sortArray);
foreach ( $sortArray as $key=>$val ) {
$newArray[] = $dataArray[$key];
}
If you need it reversed, just add in a call to array_reverse() at the end.
I think what the OP wants is to sort the first array by the second array's values.
IE- the second array is the vote count for the first array's web pages.
This could be solved more simply if in the first array you have each element as an array with two elements in it, webpage & vote count
$pages = Array
(
array(
'page' => 'http://stackoverflow.com/questions/640805/open-source-ios-components-reusable-views-controllers-buttons-table-cells-e',
'count' => 0
)
array(
'page' => 'http://stackoverflow.com/questions/3889634/fast-and-lean-pdf-viewer-for-iphone-ipad-ios-tips-and-hints',
'count' => -1
)
// etc for the rest...
)
But since the question asked how to do it in the current data structure:
$sorted_values = asort($pages);
$new_pages = array();
$sorted_keys = array_keys($sorted_values);
foreach($sorted_keys as $page_key)
array_push($new_pages, $pages[$page_key]);

Categories