Search code examples
phparraysmultidimensional-arrayarray-multisort

How to merge sub-arrays based on first value 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.


Solution

  • 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);