[英]Given an array in PHP where the contents are strings separated by commas, how do I extract the first part of string?
我有一個名為“ single.txt”的文件。 內容如下:
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...
)
首先,當一個新人注冊時,它將他們與他們的信息一起添加到.txt文件的末尾。 我希望能夠檢查他們是否已經注冊,並且編寫了以下函數:
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;
}
}
但這似乎不起作用。
如何將字符串的第一部分(即名稱部分)與檢查人員的名字進行比較?
謝謝!
嘗試這樣的事情...您可能需要根據文本的輸入方式對其稍加修改,但應該可以使您走上正確的軌道:)
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
}
循環時,您正在“切片”同一陣列。 看起來您只需要一個簡單的strpos()
:
if(strpos($content[$i], $person . ',') === 0){
return ...
}
這是不需要for
循環的另一種方式:
$names = array_map('reset', array_map('str_getcsv', $content));
if(in_array($person, $names)){
...
}
之所以有效,是因為您的數據似乎使用CSV格式
您可以像這樣循環遍歷數組中的元素:
foreach ($content as $record) {
// $record now contains string "Ada Lovelace,F,96,ISTJ,Linux,24,99"
}
您可以使用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
將它們放在一起,您將獲得類似以下內容的信息:
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.