如何获取数组中字符串的索引? array_search()不起作用

时间:2017-08-03 21:04:15

标签: php arrays search

我正在使用文本文件作为数据库,我正在尝试获取索引值。 文本文件:

0982|Chiara|chiaramella|543254
7134|Paolo|pablo752|675474
9564|Andrea|andry8239|39377874
3122|Luca|luka7|26887543
4456|Riccardo|riccard904|6832787645
9721|Fabio|fab78|38307696
3284|Francesco|frafra54|9325454
9555|Luigi|lulu14|0055468
1485|Matteo|matty990|897103464
0986|Laura|lau3245|324891000
3714|Claudio|cla235|36464820
9986|Giovanni|giojo982|0005405
8244|Stefano|stefy734|45367
7731|Marco|markkkk998|355647689
2123|Roberto|robn88|809678741

和这段代码来获取索引:

$db_friends = file("db_friends.txt");
$db_friends = array_map('trim', $db_friends);
$key = array_search('7134', $db_friends);
echo $key;

回声结果,应该给我“1”,但也许有一个错误,因为总是空的,我不知道为什么?有帮助吗?请!非常感谢!

5 个答案:

答案 0 :(得分:1)

array_search尝试找到确切的值,例如:

$array = ['value one'];

var_dump(array_search('one', $array)); //= false
var_dump(array_search('value one', $array)); //= 0

$db_friends类似于["2123|Roberto|robn88|809678741", "0982|Chiara..."],其中没有任何具有“2123”的值,因此array_search不起作用。

要解决此问题,您可以使用explode()创建另一个数组,然后使用array_search找到它:

$file = file('db_friends.txt');

foreach($file as $line){
     $db_friends[] = explode('|', trim($line));
}

$key = array_search('7134', array_column($db_friends, '0'));

echo $key; //= 1

在这种情况下,我们在另一个内部创建一个新数组(因为explode()),我们尝试在这个新数组的第一列中找到7134

答案 1 :(得分:0)

您可以迭代每一行,检查该行是否以该ID开头。

完整代码:

$db_friends = file("db_friends.txt");
$rows = array_map('trim', $db_friends);
$id = '7134';
$index = -1;

foreach ($rows as $i => $row) {
    if (substr($row, 0, strlen($id)) === $id) {
        $index = $i;
    }
}

// $index now contains the index of the row


// As a function
function getIndexOfIdInFile($file, $id) {
    $file = file("db_friends.txt");
    $file = array_map('trim', $file);

    foreach ($file as $i => $row) {
        if (substr($row, 0, strlen($id)) === $id) {
            // Return the index of the id if we have found it
            return $i;
        }
    }

    // Return -1 if the id cannot be found
    return -1;
}

答案 2 :(得分:0)

array_search仅匹配与完全匹配的数组元素,而不匹配包含给定字符串的数组元素,但具有更多。

您可以先提取每个字符串的数值,然后继续array_search,如下所示:

$key = array_search('7134', array_map('intval', $db_friends));

答案 3 :(得分:0)

您应该将数组转换为关联数组。

@Component({
  selector: 'app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.less'],
  providers: [CompanyService]
})
export class EeeComponent implements OnInit {
  target: any;
  error: CustomError;

  constructor(
      private route: ActivatedRoute,
  ) {}

  ngOnInit(): void {
      this.route.params
          .switchMap((params: Params) => this.companyService.getCompany(params['id']))
        .subscribe(
            (company) => this.target = company,
            (error) => {
              // Can't reach this !
              this.error = error;
            }
        );
    }
}

然后你可以这样做:

$db_friends_assoc = array();
foreach ($db_friends as $friend) {
    list($id, $lastname, $username, $code) = explode('|', $friend);
    $db_friends_assoc[$id] = array('lastname' => $lastname, 'username' => $username, 'code' => $code);
}

答案 4 :(得分:0)

array_search()工作正常 - 这是你的期望是错误的。 array_search()函数在数组中查找一个元素,该元素只包含 作为参数传递的值,而不是包含,以搜索值开头或结尾的值。

如果数据集中的第一个值是唯一的,那么您可以将其用作数组索引:

$data=array();
$f=fopen('yourfile.txt', 'r');
While (($r=fgetcsv($f, 0, '|') && !feof($f)) {
  $i=array_shift($r);
  $data[$i]=$r;
}

print_r $data['7134'];

或者只是......

preg_match('/\n7134\|(.*)/', file_get_contents('yourfile.txt'), $matches);
print $matches[0];

但是,使用文件来维护数据不能很好地扩展 - 容量,并发性和性能都存在问题。这就是为什么我们使用像mongodb或mysql这样的DBMS。