【问题标题】:Php: Strlen() vs. count () Problems: Warning: strlen() expects parameter 1 to be string, array givenphp: strlen() vs. count() 问题:警告:strlen() 期望参数 1 是字符串,给定数组
【发布时间】:2017-10-10 12:59:02
【问题描述】:

我使用这些代码将电话号码字符串拆分为区号和电话号码。

当我使用“strlen($areacode)”时,我得到一个 php 警告 strlen() 期望参数 1 是字符串,给定数组。

当使用count() 而不是strlen() 时,脚本执行错误。我得到结果“找不到区号”。

是什么让我错了?

<?php
$phonenumber = '0349152023';
$link = mysqli_connect('host', 'DB', 'Pass','User') or die(mysqli_error());
$db_selected = mysqli_select_db( $link, 'DB');
$ErsteDrei = substr($phonenumber,0,3); 
$array = array();
$query = mysqli_query($link, "SELECT Areacode FROM `Areacodes` WHERE Vorwahl like '".$ErsteDrei."%' ORDER BY CHAR_LENGTH(Vorwahl) DESC");
while($row = mysqli_fetch_assoc($query)){
  $array[] = $row;
}
foreach ($array as $areacode) {
    $subString = substr($phonenumber, 0, strlen($areacode));
    if ($subString == $areacode) {
        $phone = $subString." ".substr($phonenumber, strlen($areacode));
    }
}
if (!empty($phone)) {
    echo $phone;
}

else {
    echo "No AreaCode found.";
}
?>

【问题讨论】:

  • if (empty($phone)) { echo "No AreaCode found.";我不确定,但试试这样。
  • $row 是一个有 1 个索引的数组,$row['Areacode']。所以要么像这样分配它,要么根据需要访问循环中的索引$areacode['Areacode']
  • 执行 var_dump($array) 以了解结构以及如何调用您正在访问的数组中的元素;可能会有所帮助。
  • 了解strlen()count()。它们是具有不同用途的不同功能。

标签: php mysql phone-number


【解决方案1】:

这里发生的事情是您正在以关联数组“mysqli_fetch_assoc”的形式获取数据。 所以每个$row 实际上都是一个这样的数组:

array("Areacode"=>"0349"); //or whatever the code is

您可以执行以下操作:

foreach ($array as $areacode) {
    $subString = substr($phonenumber, 0, strlen($areacode["areacode"]));
    if ($subString == $areacode) {
        $phone = $subString." ".substr($phonenumber, strlen($areacode));
    }
}

或者使用“mysqli_fetch_array”代替“mysqli_fetch_assoc

【讨论】:

  • 希望如果它对你有帮助,我的答案就是解决方案:)
猜你喜欢
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多