简体   繁体   English

给定PHP中的数组,其中的内容是用逗号分隔的字符串,如何提取字符串的第一部分?

[英]Given an array in PHP where the contents are strings separated by commas, how do I extract the first part of string?

I have a file called "single.txt". 我有一个名为“ single.txt”的文件。 The contents look like: 内容如下:

Array ( [0] => Ada Lovelace,F,96,ISTJ,Linux,24,99 
        [1] => Adele Goldberg,F,65,ENFJ,Windows,50,70 
        [2] => Alan Turing,M,41,ESTP,Mac OS X,31,50...
      )

First, when a new person signs up, it adds them with them with their info to the end of the .txt file. 首先,当一个新人注册时,它将他们与他们的信息一起添加到.txt文件的末尾。 I want to be able to check whether they've already signed up and I've written the following function: 我希望能够检查他们是否已经注册,并且编写了以下函数:

function returnPerson($content){
    global $person_name;

    for($i=0 ; $i < count($content); $i++){

        if($person_name == array_slice($content,0,0)){
            $person = $content[$i];
            return $person;

        } else continue;

    }

}

But that doesn't seem to be working. 但这似乎不起作用。

How can I compare the first part of the string, ie the name part, to the name of the person checking? 如何将字符串的第一部分(即名称部分)与检查人员的名字进行比较?

Thanks! 谢谢!

Try something like this... you may have to modify it slightly depending on how your text is coming in, but should get you on the right track :) 尝试这样的事情...您可能需要根据文本的输入方式对其稍加修改,但应该可以使您走上正确的轨道:)

function returnPerson($content){
    global $person_name;

    foreach($content as $profile) {
        $profile = explode(',', $profile);

        if ($person_name == $profile[0]) {
            // Person Exists
            return $profile;
        }
    }

    return false; // person does not exist
}

You're "slicing" the same array while you're looping it. 循环时,您正在“切片”同一阵列。 It looks like you just need a simple strpos() : 看起来您只需要一个简单的strpos()

if(strpos($content[$i], $person . ',') === 0){
  return ...
}

Here's another way that doesn't require a for loop: 这是不需要for循环的另一种方式:

$names = array_map('reset', array_map('str_getcsv', $content));

if(in_array($person, $names)){
  ...
}      

It works because your data seems to use the CSV format 之所以有效,是因为您的数据似乎使用CSV格式

You can loop over the elements in the array like this: 您可以像这样循环遍历数组中的元素:

foreach ($content as $record) {
    // $record now contains string "Ada Lovelace,F,96,ISTJ,Linux,24,99"
}

You can extract fields from a comma-separated string by using the explode() function: 您可以使用explode()函数从逗号分隔的字符串中提取字段:

$string = "Ada Lovelace,F,96,ISTJ,Linux,24,99";
$fields = explode(',', $string);
// $fields[0] now contains "Ada Lovelace"
// $fields[1] now comtains "F"
// ... etc

Putting those together, you'll get something like: 将它们放在一起,您将获得类似以下内容的信息:

foreach ($content as $record) {
    $fields = explode(',', $record);
    if ($fields[0] == $name_to_check) {
        // found it
    }
}
// didn't find it

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM