| 
	
 | 
 Posted by tim on 05/20/06 16:08 
aqazi@inbox.com wrote: 
> Hi guys I am having a problem with arrayu manipulation. 
> 
> in my php script i am reading from a csv file. 
> the content of file is like this: 
> 
> name,color,quantity,price; 
> apple,red,10,$2; 
> mango,green,12,$2.5; 
> orange,orange,8,$1.5; 
> 
> I am reading the file like this: 
> 
>   $userFile = fopen("data/user.csv", "r"); 
>   $data = array(); 
>   $record = array(); 
> 
>   while (($record = fgetcsv($userFile, 1000, ",")) !== FALSE) 
>   { 
>     array_push($data,$record); 
>   } 
>   fclose($userFile); 
> 
> Now if I want to change the quantity of mango what I have to do. I am 
> trying to do something, like this but it's not entirly correct. 
> 
>   foreach($data as $value) 
>   { 
> 
>     if(((strcasecmp("mango", $value[0]) == 0)) 
>     { 
>       echo $value[1].NL; 
>       $data[$value][1] = "1"; 
>       echo $data[$value][0].NL; 
>     } 
>   } 
> 
> Can anyone give me a hint how can I change the value here. 
> 
> Any help will be grealty appreciated. 
> 
> Thanks 
> aqazi 
 
 
Hi aqazi 
 
These line aren't doing what you expect they were 
>       $data[$value][1] = "1";* 
>       echo $data[$value][0].NL; 
 
$value is always an array so its trying to access the $data array with 
an invalid index. 
 
Earlier on in the script you use 
>     array_push($data,$record); 
 
The first $record you push onto $data will have an index of 0, the next 
record will have an index of 1 etc 
 
So if you change the foreach loop later on to 
 
//                             v v 
   foreach($data as $index => $value) 
   { 
 
     // you may be able to use.... if ( $value[0] == 'mango') { 
     // if not then use '===' not '==' for checking the return value of 
strcasecmp 
 
     if(((strcasecmp("mango", $value[0]) === 0)) 
     { 
       echo $value[2]."\n"; 
       $data[$index][2] = "1"; 
       echo $data[$index][0]."\n"; 
    } 
} 
 
If you use strcasecmp then you must use '===' not '==', strcasecmp may 
return false. Using the '== 0' will give you the wrong result when 
strcasecmp return false because false has a numeric value of 0.  It 
will give the impression 'mango' was found whether it was in the string 
or not.  
 
Tim
 
  
Navigation:
[Reply to this message] 
 |