<?php /** * json字符串转换为这种格式的思路 汽车 33013 26017 11352 * 涉及函数 * json_decode()对 JSON 格式的字符串进行编码 * objarray_to_array()对象转数组 * count()获取数组总数 * array_values()去除键名 * implode(' ',数组)数组转字符串 */ $arr = array( 'key'=>'d7de53fb42e545fa96af5f618d623deb', 'kws' => '1,2,3,4,5,6,7,8,9,10' ); $url = 'http://api.91cha.com/index'; $jsonData = _request_post($url,$arr); //解析完数组以后 是一个对象数组的形式。 $arr = array(json_decode($jsonData)); //对象转数组 //调用这个函数强制转化对象为数组方便操作 $newArr = objarray_to_array($arr); //让数组看起来不那么繁琐,具体定位到$newArr[0]['data'] $twoArr = $newArr[0]['data']; //定义一个新数组 $keyArr = array(); foreach($twoArr as $k=>$v) { foreach($v as $key=>$val) { //给新数组赋键名,用新建名替换目标键名,同时产生一个新数组,$keyArr,其数组value值就是对应的数组value值 $keyArr['name'] = $v['keyword']; $keyArr['baidu'] = $v['allindex']; $keyArr['mobile'] = $v['mobileindex']; $keyArr['qh360'] = $v['so360index']; } $sqlWhere = dealparam($keyArr); $sql = 'SELECT * FROM tb_name WHERE '.$sqlWhere; //echo $sql; echo '<br />'; } /** * 对象转数组 * @param $obj * @return array */ function objarray_to_array($obj) { //定义数组 $ret = array(); //foreach遍历 foreach ($obj as $key => $value) { //判断键值是对象还是数组 if (gettype($value) == "array" || gettype($value) == "object"){ //采用对象转数组函数 $ret[$key] = objarray_to_array($value); }else{ $ret[$key] = $value; } } return $ret; } /** * 拼接where条件 * */ function dealparam($param) { $url = array(); if(!empty($param)){ foreach ($param as $k=>$v) { if($v !== '') { $sqlWhere[] = $k.'="'.$v.'"'; // $sqlWhere[] = $k.'='.$v; } } } return !empty($sqlWhere) ? implode(' AND ', $sqlWhere) : ''; } //模拟页面 function _request_post($url = '', $post_data = array()) { if ( empty ( $url ) || empty ( $post_data )) { return false; } $o = ""; foreach ( $post_data as $k => $v ) { $o .= "$k=" . urlencode ( $v ) . "&"; } $post_data = substr ( $o, 0, - 1 ); $postUrl = $url; $curlPost = $post_data; $ch = curl_init (); //初始化curl curl_setopt ( $ch, CURLOPT_URL, $postUrl ); //抓取指定网页 curl_setopt ( $ch, CURLOPT_HEADER, 0 ); //设置header curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); //要求结果为字符串且输出到屏幕上 curl_setopt ( $ch, CURLOPT_POST, 1 ); //post提交方式 curl_setopt ( $ch, CURLOPT_POSTFIELDS, $curlPost ); $data = curl_exec ( $ch ); //运行curl curl_close ( $ch ); return $data; }