【问题标题】:How to extract the emails from the JSON in the PHP array?如何从 PHP 数组中的 JSON 中提取电子邮件?
【发布时间】:2011-02-22 07:13:17
【问题描述】:

如何从这个数组中获取邮件?

array(16) { 
    [0]=> string(273) ""guid":"","contactId":"44","contactName":"_, atri","email":"atri_megrez@yahoo.com","emaillink":"http:\/\/mrd.mail.yahoo.com\/compose?To=atri_megrez%40yahoo.com","isConnection":false,"connection":"","displayImg":null,"msgrID":"atri_megrez","msgrStatus":"","isMsgrBuddy":122}," 
    [1]=> string(260) ""guid":"","contactId":"100","contactName":"afrin","email":"fida_cuty123@yahoo.com","emaillink":"http:\/\/mrd.mail.yahoo.com\/compose?To=fida_cuty123%40yahoo.com","isConnection":false,"connection":"","displayImg":null,"msgrID":"","msgrStatus":"","isMsgrBuddy":false}," 
    [2]=> string(258) ""guid":"","contactId":"101","contactName":"afrin","email":"waliyani@yahoo.com","emaillink":"http:\/\/mrd.mail.yahoo.com\/compose?To=waliyani%40yahoo.com","isConnection":false,"connection":"","displayImg":null,"msgrID":"","msgrStatus":"","isMsgrBuddy":false},"
}

【问题讨论】:

  • 请你让你的数组有点可读性好吗?可能是从"<pre>".print_r(arr)."</pre>" 复制输出并粘贴。

标签: php arrays json


【解决方案1】:

看起来该数组中的每个字符串都是JSON 数据。

如果您使用的是现代版本的 PHP,则可以使用 json_decode() 将数据转换为可用格式。

foreach($array as $string) {
    $json = json_decode($string);
    echo "Email = {$json->email}\n";
}

【讨论】:

  • 字符串中缺少开头的{ 括号,而结尾的括号在那里。将其添加到您的 json_decode 调用中。
【解决方案2】:

如果您可以发布一个数据示例(例如:它来自哪里,数组的print_r() 输出的格式正确的示例)会有所帮助,但是从我可以收集到的数据中,这将获得来自数组:

/* Make $array hold the given array */

$emails = array();
foreach($array as $contact){
    $emails[] = $contact['email'];
}

// All emails
print_r($emails);

【讨论】:

  • @Charles 的答案是正确的方法,现在我可以看到您正在使用 JSON 数据
【解决方案3】:

您可以对每个数组元素运行正则表达式。像这样:/"email":"(.+?)"/

$emails = array();
foreach ($array as $str)
{
    if (preg_match('/"email":"(.+?)"/', $str, $matches))
    {
        $emails[] = $matches[1];
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多