1

if i may i'd like to ask how to search a max value of column of CSV file using PHP or Javascipt,

this is my csv file table:

image,category,prob
"data/test1.jpg",zero1,0.947648
"data/test1.jpg",zero1,0.957323
"data/test1.jpg",zero1,0.955677
"data/test1.jpg",zero1,0.951940
"data/test1.jpg",zero1,0.950025

i'd like to find the highest value of prob column and print the category value of it.

output i looking for is like this:

zero1,0.957323

thanks for any help

ironGiant
  • 13
  • 4

2 Answers2

0

In PHP you could use fgetcsv to read the data:

$handle = fopen("test.csv", "r");
// read the headers
$data = fgetcsv($handle);
// read the data
$max_prob = 0;
$category_max = '';
while (($data = fgetcsv($handle)) !== false) {
    if ($data[2] > $max_prob) {
        $max_prob = $data[2];
        $category_max = $data[1];
    }
}
echo "max prob value is $max_prob for category $category_max\n";
Nick
  • 138,499
  • 22
  • 57
  • 95
0

OK, so typically on SO, you want to say what you've tried, what error you've gotten etc, otherwise your question may get deleted. But, here goes:

var originalString = `"data/test1.jpg",zero1,0.947648
    "data/test1.jpg",zero1,0.957323
    "data/test1.jpg",zero1,0.955677
    "data/test1.jpg",zero1,0.951940
    "data/test1.jpg",zero1,0.950025`;

var oneDArray = originalString.split('\n\r'); // split on the return characters, you may have to play with this to get it to work.

var twoDAttay = oneDArray.map( line => line.split(",") ); // make an array of 3 elements for each line, split by the commas.

So at this point you have this:

twoDArray = [
    ["data/test1.jpg",zero1,0.947648],
    ["data/test1.jpg",zero1,0.957323],
    ["data/test1.jpg",zero1,0.955677],
    ["data/test1.jpg",zero1,0.951940],
    ["data/test1.jpg",zero1,0.950025]
];

And all your numbers are in the 2 spot of each inner array. Now we're ready to find the maximum number, we just need to get the numbers in their own array:

var numArray = twoDArray.map( line => Number( line[2] )); // get only the numbers
var maxNum = Math.max( ...numArray );   // find the maximum number
var index = numArray.indexOf( maxNum ); // find the index of the max number, this will correspond to the oneDArray.
var maxLine = oneDarray[ index ];       // This is your answer

But after you get the 2-D array, there's many ways you can do it: Finding the max value of an attribute in an array of objects. Use the version that makes the most sense to you. The hardest part is going to be cleaning your data into a format that js can understand - those quoted and unquoted strings are going to be an issue.

Travis Heeter
  • 13,002
  • 13
  • 87
  • 129