Sorting 2D array by matching different column value

49
January 12, 2021, at 00:20 AM

I have a 2D array like this:

3 6 4
4 3 ""
5 "" 6
6 5 3

I would like to sort it matching the first and last column value. For the first array, the second column needs to be empty (done it myself). For the last array, the third column needs to be empty (done it myself).

My question is, how can I sort the rest of the array, by matching the first and last column value. The first column of the second array, need to match the third column of the first array.

Here is the first array:

5 "" 6

Because the third column of it is 6, so I need to find an array that has 6 as its first column. The second array will be:

6 5 3

After sorting the array, the array will be like this (please ignore the space):

5 "" 6
     6 5 3
         3 6 4
             4 3 ""

Here is my attempt:

echo "first node: " . $first[0][0];
echo "<br>";
//order the node
$next_node = $first[0][2];
$orderd_node = array();
  for ($a = 0; $a < 2; $a++) {
    for($i = 0; $i < $count - 2; $i++) {
      if ($next_node == $node[$i][1]) {
        $n = $i+2;
        echo "node" . $n . ": " . $next_node;
        $next_node = $node[$i][2];
        echo "<br>";
        echo $next_node;
        array_push($orderd_node, $next_node);
        echo "<br>";
      }
    }
  }

echo "last node: " . $last[0][0];
echo "<br>";

I expect to get an output like this, which sort the array and print the first column of each array:

first node: 5
node2: 6
node3: 3
last node: 4

However, I get a wrong output:

first node: 5
node2: 6
4
last node: 4

This is my other attempt:

$str = "" . $first[0][0] . $first[0][1] . $first[0][2] ;
$cp_count = $count;
for ($i = 0; ($i < $count-2); $i++) {
  if($str[strlen($str)-1] == $node[$i][0]){
    for ($j = 0; $j < 2; $j++) {
      $str = $str . $node[$i][$j+1];
    }
    echo $str;
  }
}

I expect to get an output like this, which sort the array and print each array except printing the match column again:

5653643

However, I get a wrong output:

5653
READ ALSO
Cannot connect to MySQL server in Dreamweaver MX 2004

Cannot connect to MySQL server in Dreamweaver MX 2004

I am trying in Dreamweaver MX 2004 to connect to MySQL database

37
Face detection not showing in correct position

Face detection not showing in correct position

my face Detection app doesnt work correctly even though I have added the correct mathThe borders are shown in different areas

32
Correct use of Jest test with rejects.toEqual

Correct use of Jest test with rejects.toEqual

I am trying to use jest library:

55
How to locales word in side export default?

How to locales word in side export default?

I have been trying to change the language from English to others,

44