开发者

finding array values and comparing them?

开发者 https://www.devze.com 2023-01-23 18:21 出处:网络
ha15rs,250,home2.gif,2 ha36gs,150,home3.gif,1 ha27se,300,home4.gif,4 ha4678,200,home5.gif,5 when i turn this text file into array $handle, how can i test the second field (250,150,300,20开发者_Stack
ha15rs,250,home2.gif,2
ha36gs,150,home3.gif,1
ha27se,300,home4.gif,4
ha4678,200,home5.gif,5

when i turn this text file into array $handle, how can i test the second field (250,150,300,20开发者_StackOverflow中文版0)

i want to check if its below 100, if it is then display the row!!

if $secondfield < 100

then echo 

how could i manipulate the array to do this in php thanks ?


Simple..

$h = file("file_name");

for ($x = 0; $x < count($h); $x++)
{
   $a = explode(",", $h[$x]);
   if ($a[1] < 100)
        echo $h[$x];
}


I presume you have each line in the file as an element in your array. In that case:

$data = array_map(function($e){ return explode(',', $e); }, $array);
$desiredData = array_filter(function($e){ return $e[1] < 100; }, $data);


Explode every string, so you have four arrays:

foreach($strings as $string){
  $arr = expode(',', $string);

  if( intval($arr[1]) < 100 ){
    echo $string;
  }
}


Assuming you have a csv (I copied and modified some code from the php manual):

if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($line = fgets($handle)) !== FALSE) {
        $data = str_getcsv($line);
        if ($data[1] < 100)
            echo $line;
    }
    fclose($handle);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号