通过层级键在多维数组中获取目标值
1 /* 2 *Author : @YunGaZeon 3 *Date : 2017.08.09 4 *param data : Data Array 5 *param keys : Key level Array 6 *return : Array 7 */ 8 function findbykeys($data,$keys,$_index=0,&$_target_arr=[]) 9 { 10 if($_index>(count($keys)-1)) 11 return $_target_arr; 12 13 foreach($data as $k=>$v) 14 { 15 if($k===$keys[$_index]) 16 { 17 if($_index==(count($keys)-1)) 18 $_target_arr[]=$v; 19 else 20 { 21 if(is_array($v)) 22 findbykeys($v,$keys,++$_index,$_target_arr); 23 } 24 } 25 else 26 { 27 if(is_array($v)) 28 findbykeys($v,$keys,$_index,$_target_arr); 29 } 30 } 31 return $_target_arr; 32 }
使用:获取京东某页评价中的所有图片链接
1 $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'); 2 $data=iconv('GBK', 'UTF-8//TRANSLIT//IGNORE', $data); 3 preg_match('/^[^(]+(([sS]+));$/',$data,$data); 4 $data=$data[1]; 5 $cm=json_decode($data,true); 6 $keys=['comments','images','imgUrl']; 7 var_dump(findbykeys($cm,$keys));