Я смотрю вокруг, надеясь, что смогу найти проблему, над которой я спотыкаюсь... Однако я не мог ее найти. Я создал класс на PHP, внутри этого класса есть функция, которая соединяется с API, получающим данные JSON (эта функция была протестирована и работает как шарм). Однако теперь я пытаюсь отделить объекты данных JSON, которые получаю в разных функциях.
Мне только удалось проанализировать данные сейчас через foreach и echo, но было бы бесполезно делать это так постоянно.
Это то, что в настоящее время выглядит так, что вы получаете идею.
РЕДАКТИРОВАТЬ
Проблема решена, public function foo();
Had и переменная $info
которой был json_decode();
которые перегруппировали следующую функцию для разделения данных.
class parseData{
var $name;
var $domain;
public function foo($name, $domain)
{
$this->name = $name;
$this->domain = $domain;
$ch = curl_init();
$user_agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31';
$request_headers = array();
$request_headers[] = 'User-Agent: ' . $user_agent;
$request_headers[] = 'Accept: text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8';
curl_setopt($ch, CURLOPT_URL, "https://www.xxx." . $domain . "/api/public/users?name=" . $name . "");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, "https://www.xxx." . $domain . "/api/public/users?name=" . $name);
$id = json_decode(curl_exec($ch));
if (isset($id) && $id->profileVisible == 1) {
curl_setopt($ch, CURLOPT_URL, "https://www.xxx." . $domain . "/api/public/users/" . $id->uniqueId . "/profile");
$info = curl_exec($ch);
} else
$info = false;
curl_close($ch);
return $info;
}
public $response = array(), $user = array(), $friends = array(), $groups = array(), $rooms = array(), $badges = array();
public function __construct(){
$this->response = $this->foo("user", "nl");
$this->init();
}
// this function will split data into sub variables
private function init(){
$this->response =json_decode(file_get_contents($this->response), TRUE);
$this->user = $this->response['user'];
$this->friends = $this->response['friends'];
$this->groups = $this->response['groups'];
$this->rooms = $this->response['rooms'];
$this->badges = $this->response['badges'];
// free main response object
unset($this->response);
}
public function uid(){
echo $this->user['uniqueId'];
}
public function name(){
echo $this->user['name'];
}
public function membersince(){
echo $this->user['memberSince'];
}
public function motto(){
echo $this->user['motto'];
}
public function figure(){
echo $this->user['figureString'];
}
//this function will manipulate USER data.
public function user(){
echo "Naam: ".$this->user['name'].'<br/>';
echo "Motto: ".$this->user['motto'].'<br/>';
echo "Lid sinds: ".$this->user['memberSince'].'<br/>';
echo "Unique ID: ".$this->user['uniqueId'].'<br/>';
echo "figureString: ".$this->user['figureString'].'<br/>';
foreach($this->user['selectedBadges'] as $selectedBadge){
echo 'Badge index: '. $selectedBadge['badgeIndex'];
echo 'Badge code: '. $selectedBadge['code'];
echo 'Badge naam: '. $selectedBadge['name'];
echo 'Badge beschrijving: '. $selectedBadge['description'];
}
}
public function friends(){
//do stuff with $this->friends.
}
public function groups(){
//do stuff with $this->groups
}
//and other functions like badges and rooms etc.
}
$parser = new parseData();
$parser->user();
API отправляет разные объекты назад, и я хотел бы разделить их на разные functions
как "пользователь", "друзья", "группы" и т.д., Чтобы извлечь все строки из этих объектов. Поэтому мой вопрос заключается в возможности анализировать данные API через различные функции в одном классе? Если да, то как мне это сделать? И вызов функции будет более простой задачей, чтобы сделать это, или это будет просто хлопот, как делать метод foreach
?
Итак, я просмотрел ваш json
и вам это может понравиться
class parseData{
public $response = array(), $user = array(), $friends = array(), $groups = array(), $rooms = array(), $badges = array();
public function __construct(){
$this->response = call_your_function_get_api_response();
$this->init();
}
// this function will split data into sub variables
private function init(){
$this->response = json_decode(file_get_contents('json.json'), TRUE);
//I'm using file get contents here, as I've stored your json into file.
// but you'll have to do like this
//$this->response = json_decode($this->response, TRUE);
$this->user = $this->response['user'];
$this->friends = $this->response['friends'];
$this->groups = $this->response['groups'];
$this->rooms = $this->response['rooms'];
$this->badges = $this->response['badges'];
// free main response object
unset($this->response);
}
/*
* I'm updating here with new function name(), so to print name only do this.
*/
public function name(){
echo "Name: ".$this->user['name'].'<br/>'; //This will print name only.
}
//this function will manipulate USER data.
public function user(){
echo "User Unique ID: ".$this->user['uniqueId'].'<br/>';
echo "Name: ".$this->user['name'].'<br/>';
echo "figureString: ".$this->user['figureString'].'<br/>';
foreach($this->user['selectedBadges'] as $selectedBadge){
echo 'Badge index: '. $selectedBadge['badgeIndex'];
echo 'Badge code: '. $selectedBadge['code'];
echo 'Badge name: '. $selectedBadge['name'];
echo 'Badge description: '. $selectedBadge['description'];
}
}
public function friends(){
//do stuff with $this->friends.
}
public function groups(){
//do stuff with $this->groups
}
//and other functions like badges and rooms etc.
}
$parser = new parseData();
$parser->user();
/*
* and you can call function like this
* $parser->friends(); will process only friends data from json response
* $parser->groups(); will process only groups data from json response.
* ... rest of functions ...
*/
Я тестировал это с помощью одной итерации материала, используя users() function
.
здесь выводится
редактировать
Я обновил class
с новым name()
метода name()
чтобы теперь печатать только имя,
$parser->name();
Другое редактирование
согласно вашему комментарию
Я снова помещаю код __construct()
.
public function __construct(){
$get = new foo();
$this->response = $get->bar("person", "nl");
$this->init();
}
и все остальное одинаково.
$parser = new parseData();
$parser->user();
$parser->name(); //will display name only.
все вместе
вам необходимо обновить две functions
public function __construct(){
$this->response = json_decode($this->foo("user", "nl"), TRUE);
$this->init();
}
и в init()
закомментируйте первую строку, поскольку она больше не нужна.
Надеюсь, что это поможет вам.