【发布时间】: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) 以了解结构以及如何调用您正在访问的数组中的元素;可能会有所帮助。
标签: php mysql phone-number