在PHP中从JSON数据中读取和存储变量

时间:2016-07-09 12:44:54

标签: php json

我有以下带有id的JSON数据。最后:

[{"Name":"malek","Email":"malek@bar.com","Donation":"5","Type":"Cash","id":0},{"Name":"donnie","Email":"donnie@bar.com","Donation":"6","Type":"Cheque","id":1},{"Name":"ramanuj","Email":"ramanuj@bar.com","Donation":"3","Type":"NEFT","id":2},{"Name":"neha","Email":"neha@bar.com","Donation":"2","Type":"RTGS","id":3},{"Name":"aasha","Email":"aasha@bar.com","Donation":"1","Type":"CC","id":4},{"Name":"zia","Email":"zia@bar.com","Donation":"6","Type":"PayU","id":5},{"Name":"John","Email":"John@bar.com","Donation":"7","Type":"Instamojo","id":6}]

我想专门获取John的电子邮件:并将其存储在变量$ johnemail中,以便$ johnemail =='John@bar.com'

最简单的方法是什么?

1 个答案:

答案 0 :(得分:0)

使用json_decodearray_column(自PHP 5.5起可用)和array_search函数的简单解决方案:

$json_data = '[{"Name":"malek","Email":"malek@bar.com","Donation":"5","Type":"Cash","id":0},{"Name":"donnie","Email":"donnie@bar.com","Donation":"6","Type":"Cheque","id":1},{"Name":"ramanuj","Email":"ramanuj@bar.com","Donation":"3","Type":"NEFT","id":2},{"Name":"neha","Email":"neha@bar.com","Donation":"2","Type":"RTGS","id":3},{"Name":"aasha","Email":"aasha@bar.com","Donation":"1","Type":"CC","id":4},{"Name":"zia","Email":"zia@bar.com","Donation":"6","Type":"PayU","id":5},{"Name":"John","Email":"John@bar.com","Donation":"7","Type":"Instamojo","id":6}]';

$search_name = 'John';
$items = json_decode($json_data, TRUE);
$emails = array_column($items, 'Name', 'Email');   // email is good for using as array key, as it should be unique
$johnemail = array_search($search_name, $emails);  // note that this is case-sensitive search 

print_r($johnemail);  // "John@bar.com"