PHP重命名字符串(如果字符串已经存在)


PHP renaming string if string already exists

我正在数组中存储一些数据,如果标题已经存在于数组中,我想向其添加键。但出于某种原因,它并没有为标题添加关键。

这是我的循环:

$data = [];
foreach ($urls as $key => $url) {
  $local = [];
  $html = file_get_contents($url);
  $crawler = new Crawler($html);
  $headers = $crawler->filter('h1.title');
  $title = $headers->text();
  $lowertitle = strtolower($title);
  if (in_array($lowertitle, $local)) {
    $lowertitle = $lowertitle.$key;
  }
  $local = [
    'title' => $lowertitle,
  ];
  $data[] = $local;
}
echo "<pre>";
var_dump($data);
echo "</pre>";

您在这里找不到任何东西:

foreach ($urls as $key => $url) {
  $local = [];
  // $local does not change here...
  // So here $local is an empty array
  if (in_array($lowertitle, $local)) {
    $lowertitle = $lowertitle.$key;
  }
  ...

如果你想检查标题是否已经存在于$data数组中,你有几个选项:

  • 循环遍历整个数组或使用数组筛选函数来查看标题是否存在于$data
  • 使用小写标题作为$data数组的关键字。这样您就可以轻松地检查重复值

我会使用第二个选项或类似的东西。

一个简单的例子:

if (array_key_exists($lowertitle, $data)) {
  $lowertitle = $lowertitle.$key;
}
...
$data[$lowertitle] = $local;