我需要从 mysql 数据库生成一个包含姓名、电子邮件和电话号码的表。我正在使用 php 来创建表格,除了如何获取某个人的电话号码(如果存在)之外,我已经弄清楚了其中的大部分内容。这很棘手,因为与姓名和电子邮件不同,如果存在信息,则没有特殊字段(不是每个人都提供电话号码)。如果电话号码存在,它会包含在“params”字段中,并带有一堆其他数据。我的代码使用以下语句生成表格:
while($row = mysql_fetch_array($result))
为了显示我需要筛选的数据是什么样子,我执行了“print_r 命令,其结果是:
Array ( [0] => Manager [usertype] => Manager [1] => 167 [id] => 167 [2] => Sam Spade [Name] => Sam Spade [3] => sm@aol.com [Email] => sm@aol.com [4] => 167 [user_id] => 167 [5] => {"birth_year":"1911","ride_note":"on","membership_visible":"on","volunteer":["","House Events","House Socials"],"ride_catagory":["10-12","13-15"],"phone":"540-123-4567"} [params] => {"birth_year":"1911","ride_note":"on","membership_visible":"on","volunteer":["","House Events","House Socials"],"ride_catagory":["10-12","13-15"],"phone":"540-123-4567"} )
如何提取电话号码 540-123-4567? (如果没有给出电话号码,那么“电话”一词也不会出现。)
谢谢
我想我们已经接近了。让我公开我目前拥有的更多代码:
$sql = 'SELECT c.usertype, c.id, c.`name` as Name, c.`email` as Email, j.user_id, j.`params`
FROM j25_akeebasubs_users j, j25_users c WHERE j.params LIKE "%membership_visible%"
and c.id = j.user_id and usertype != "Registered" order by c.name;';
$result = mysql_query($sql) or die ('Error: '.mysql_error ());
while($row = mysql_fetch_array($result))
{
$arr = "{$arr}\n
<table border=1 cellspacing=1 cellpadding=2>
<col width=200px />
<col width=300px />
<col width=150px />
<tr>
<td>{$row['Name']}</td>
<td>{$row['Email']}</td>
<td>{$row[5]}</td>
</tr>
</table>
\n</BODY>\n</HTML>\n";
}
return ($arr);
}
姓名和电子邮件地址正常。对于最后一个元素 $row[5],我很自然地获得了所有存在的数据,我只需要从中获取电话号码。
最佳答案
假设 Marc B 是正确的,并且它在您的参数字段中是有效的 JSON,您应该能够执行如下操作:
while( $row = mysql_fetch_array($result)) {
$user_params = json_decode($row['params'], true);
$arr = "{$arr}\n
<table border=1 cellspacing=1 cellpadding=2>
<col width=200px />
<col width=300px />
<col width=150px />
<tr>
<td>{$row['Name']}</td>
<td>{$row['Email']}</td>
<td>{$user_params['phone']}</td>
</tr>
</table>
\n</BODY>\n</HTML>\n";
}
return $arr;
请参阅 json_decode 的 PHP 文档
关于php - 在 Php 数组中搜索字符串并提取相邻文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22994376/