phparrays

combine php array, with matching values


I have a set of php arrays

$arrayOne = (
    0 => new,
    1 => old,
    2 => fresh,
    3 => new,
    4 => old,
    5 => fresh,
    6 => new,
    7 => old,
    8 => fresh,

    )
$arrayTwo = (
   0 => yellow,
   1 => green,
   2 => red,
   3 => blue,
   4 => grey,
   5 => orange,
   6 => purple,
   7=> pink,
   8 => brown
   )
$arrayThree = (
  0 => Monday
  1 => Tuesday
  2 => Wednesday
  3 => Thursday
  4 => Friday
  5 => Saturday
  6 => Sunday
  7 => Monday2
  8 => Monday3
  )

These array's are being looped though and placed in a table

for($index = 0; index < 100; $index++){

 $returnVariable .= '<td>'.$ArrayOne[$index].'</td>';
 $returnVariable .= '<td>'.$ArrayTwo[$index].'</td>';
 $returnVariable .= '<td>'.$ArrayThree[$index].'</td>';

}

When returned and displayed on the page the table works just as intended with everything matched how they are supposed to be

new    yellow    monday
old    green     tuesday
fresh  red       wednesday

etc,etc, I would like to group the first column so that it list all the 'new', then all the 'old', then all the fresh, while keeping the intended matching ex,

new   yellow     monday
new   blue       thursday
new   purple     sunday
old   green      tuesday
old   grey       friday
old   pink       Monday2 

etc etc


Solution

  • First, join the three arrays into one. Then, sort the new array by the first value (new first, then old, then fresh):

    <?php    
    $arrayOne = [
        0 => "new",
        1 => "old",
        2 => "fresh",
        3 => "new",
        4 => "old",
        5 => "fresh",
        6 => "new",
        7 => "old",
        8 => "fresh",
    
    ];
    $arrayTwo = [
       0 => "yellow",
       1 => "green",
       2 => "red",
       3 => "blue",
       4 => "grey",
       5 => "orange",
       6 => "purple",
       7=> "pink",
       8 => "brow"
    ];
    $arrayThree = [
      0 => "Monday",
      1 => "Tuesday",
      2 => "Wednesday",
      3 => "Thursday",
      4 => "Friday",
      5 => "Saturday",
      6 => "Sunday",
      7 => "Monday2",
      8 => "Monday3",
    ];
    echo "<pre>";
    for ($i = 0; $i < count($arrayOne); $i++) {
        $array[] = [
            $arrayOne[$i],
            $arrayTwo[$i],
            $arrayThree[$i],
        ];
    }
    $values = [ // give these strings a numeric value to compare them
        "new" => 0,
        "old" => 1,
        "fresh" => 2,
    ];
    usort($array, function($a, $b) use ($values) {
        return $values[$a[0]] - $values[$b[0]];
    });
    

    Demo