php数组中的csv值,得到一定的值?

iyr7buue  于 11个月前  发布在  PHP
关注(0)|答案(2)|浏览(96)

我有一个txt文件,其中有像下面这样的行。

apple, green, fruit
banana, yellow, fruit
carrot, orange, vegetable

字符串
我试着拿到物品,按颜色。所以如果我有绿色我想退苹果,如果我有黄色我想退香蕉。

$array = file($file_path);


其输出

Array ( [0] => apple, green, fruit
        [1] => banana, yellow, fruit
        [2] => carrot, orange, vegetable
    )


我现在想做一些类似下面的事情,在位置1找到$input,并为该行返回位置0。

$input = 'green';
$result = array_search($input, array_column($array, '1', '0')); // return apple.


但是$result返回空。我需要将CSV转换为数组吗?还是有其他方法?谢谢

o2g1uqev

o2g1uqev1#

如果你想读取你的csv文件,你可以从它开始,然后根据需要twik(这只是一个小文件的例子,不推荐大文件)

if (($open = fopen($file_path, "r")) !== false) {
    while (($data = fgetcsv($open, 1000, ",")) !== false) {
        $array[] = $data;
    }
 
    fclose($open);
}
 
// Display you array data, so you can make the right search

var_dump($array);

字符串

qvk1mo1f

qvk1mo1f2#

$array中的每个值都是一个字符串,比如“apple,绿色,fruit”,而不是像[ apple,绿色,fruit ]这样的数组。所以你首先要循环数组,把每个$value变成一个数组,让代码工作:

$array = [
  'apple, green, fruit',
  'banana, yellow, fruit',
  'carrot, orange, vegetable'
];

$input = 'green';

$arrayWithSubarrays = array_map(fn($value) => explode(', ', $value), $array);

$result = array_search($input, array_column($arrayWithSubarrays, 1, 0));

print_r($result);   // Output: apple

字符串
替代办法:
如果输入数组包含很多条目,你可能想提前离开循环。在这种情况下,array_map是一个矫枉过正的,因为它将循环所有数组条目:

$array = [
  'apple, green, fruit',
  'banana, yellow, fruit',
  'carrot, orange, vegetable'
];

$input = 'green';

$result = null;

foreach ($array as $value) {
  if (str_contains($value, ", $input, ")) {
    $result = strtok($value, ',');   // or: explode(',', value)[0]
    break;
  }
}

print_r($result);   // Output: apple


另一种可能性是过滤条目。结果将是一个数组(考虑一个多个水果具有相同颜色的情况):

$input = 'green';

$result = array_filter($array, fn($value) => str_contains($value, ", $input, "));

print_r($result);

// Output:

Array
(
    [0] => apple, green, fruit
)

相关问题