Find row in 2d array with specific value in a column and smallest value in another column

✔ Recommended Answer

Try this,

$arr = array_map(function($v){return $v[0];}, $graph);$key = array_keys($arr, min($arr));

Source: stackoverflow.com

Answered By: LF00

Method #2

To find the row in a 2D array with a specific value in a column and the smallest value in another column, you can use the following algorithm:

  1. Initialize two variables, one to store the smallest value found so far and another to store the index of the row that contains that value.
  2. Loop through each row in the 2D array.
  3. Check if the value in the specified column of the current row matches the specific value you are searching for. If it does, proceed to step 4. Otherwise, continue to the next row.
  4. Check if the value in the other specified column of the current row is smaller than the current smallest value found. If it is, update the smallest value found and the index of the row that contains it.
  5. Continue looping through each row until all rows have been checked.
  6. Return the index of the row that contains the smallest value in the specified column and the specific value in the other specified column.

Here's an example code snippet that implements this algorithm:

css
function findRowWithSpecificValueAndSmallestValue(array, specificColumn, specificValue, smallestColumn) { let smallestValue = Infinity; let index = -1; for (let i = 0; i < array.length; i++) { if (array[i][specificColumn] === specificValue) { if (array[i][smallestColumn] < smallestValue) { smallestValue = array[i][smallestColumn]; index = i; } } } return index; }

You can call this function with your 2D array, the index of the specific column you are searching for, the specific value you are searching for, and the index of the smallest column you are searching for. The function will return the index of the row that contains the smallest value in the specified column and the specific value in the other specified column.

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755