通过层级键在多维数组中获取目标值
/*
*Author : @YunGaZeon
*Date : 2017.08.09
*param data : Data Array
*param keys : Key level Array
*return : Array
*/
function findbykeys($data,$keys,$_index=0,&$_target_arr=[])
{
if($_index>(count($keys)-1))
return $_target_arr; foreach($data as $k=>$v)
{
if($k===$keys[$_index])
{
if($_index==(count($keys)-1))
$_target_arr[]=$v;
else
{
if(is_array($v))
findbykeys($v,$keys,++$_index,$_target_arr);
}
}
else
{
if(is_array($v))
findbykeys($v,$keys,$_index,$_target_arr);
}
}
return $_target_arr;
}
使用:获取京东某页评价中的所有图片链接
$data=file_get_contents('https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment&productId=5045080&score=0&sortType=5&page=1&pageSize=10&isShadowSku=0&rid=0&fold=1');
$data=iconv('GBK', 'UTF-8//TRANSLIT//IGNORE', $data);
preg_match('/^[^\(]+\(([\s\S]+)\);$/',$data,$data);
$data=$data[1];
$cm=json_decode($data,true);
$keys=['comments','images','imgUrl'];
var_dump(findbykeys($cm,$keys));