I have a txt file which has rows like below.
apple, green, fruit
banana, yellow, fruit
carrot, orange, vegetable
I am trying to get the item, by the color.
So if I have green I want to return apple, if I have yellow I want to return banana.
I do
$array = file($file_path);
Which outputs
Array ( [0] => apple, green, fruit
[1] => banana, yellow, fruit
[2] => carrot, orange, vegetable
)
I now want to do something like below, find $input in the position 1 and return position 0 for that row.
$input = 'green';
$result = array_search($input, array_column($array, '1', '0')); // return apple.
But the $result returns empty. Do I need to convert the CSV to an array, or is there another way?
Thanks
2
Answers
If you want to read your csv file; you can start with that and twik as you need
(this is just an example for small files not recommended for large ones)
Each value in $array is a string, like "apple, green, fruit", and not an array like [ apple, green, fruit ]. So you first have to loop over the array and turn each $value into an array to make your code work:
Alternative approaches:
If the input array contains a lot of entries you might want to leave the loop early. In that case array_map is an overkill as it will always loop over all array entries:
Another possibility is to filter the entries. The result will be an array (think of a case where more than one fruit is having the same color):