Я везу JSON
данные из моей базы данных riak, и я могу отобразить его с помощью print_r($data)
, но когда я пытаюсь отобразить информацию, связанную с ‘text’ в данных JSON, я получаю это сообщение об ошибке:
Предупреждение PHP: json_decode () ожидает, что параметр 1 будет строкой, объектом
приведено в /var/www/html/index.php в строке 33Предупреждение PHP: В foreach () указан неверный аргумент
/var/www/html/index.php в строке 35
<?php
require_once('src/Basho/Riak/Riak.php');
require_once('src/Basho/Riak/Bucket.php');
require_once('src/Basho/Riak/Exception.php');
require_once('src/Basho/Riak/Link.php');
require_once('src/Basho/Riak/MapReduce.php');
require_once('src/Basho/Riak/Object.php');
require_once('src/Basho/Riak/StringIO.php');
require_once('src/Basho/Riak/Utils.php');
require_once('src/Basho/Riak/Link/Phase.php');
require_once('src/Basho/Riak/MapReduce/Phase.php');
$client = new Basho\Riak\Riak('172.31.42.72', 10018);
$myBucket = $client->bucket('world'); // our bucket, world
// fetches stored raw JSON data from riak database
$fetched = $myBucket->get('542660947589230592');
//converts json string to an array
$data = json_decode($fetched, true);
foreach ($data as $tweet) {
echo $tweet->text, "<br>";
}
?>
Необработанные данные JSON — это твит от твиттера, и ДО того, как они были декодированы, я сделал простое: print_r($fetched)
проверьте, что на самом деле выбирается:
Basho\Riak\Object Object ( [meta:protected] => Array ( ) [indexes:protected] => Array ( ) [autoIndexes:protected] => Array ( ) [client] => Basho\Riak\Riak Object ( [host] => 172.31.42.72 [port] => 10018 [prefix] => riak [mapred_prefix] => mapred [indexPrefix] => buckets [clientid] => php_vpyij2 [r] => 2 [w] => 2 [dw] => 2 ) [bucket] => Basho\Riak\Bucket Object ( [client] => Basho\Riak\Riak Object ( [host] => 172.31.42.72 [port] => 10018 [prefix] => riak [mapred_prefix] => mapred [indexPrefix] => buckets [clientid] => php_vpyij2 [r] => 2 [w] => 2 [dw] => 2 ) [name] => world [r] => [w] => [dw] => ) [key] => 542660947589230592 [jsonize] => 1 [headers] => Array ( [http_code] => 200 [x-riak-vclock] => a85hYGBgzGDKBVIcJr1RG5yf1mVkMCUy5rEyMO75c5YvCwA= [vary] => Accept-Encoding [server] => MochiWeb/1.1 WebMachine/1.10.5 (jokes are better explained) [link] => ; rel="up" [last-modified] => Wed, 10 Dec 2014 12:43:45 GMT [etag] => "62oBuySAGsygcN9kgeB4ZG" [date] => Fri, 12 Dec 2014 09:58:52 GMT [content-type] => application/octet-stream [content-length] => 5026 ) [links] => Array ( ) [siblings] => [exists]
=> 1 [data] => Array ( [created_at] => Wed Dec 10 12:43:46 +0000 2014 [id] => 542660947589230592 [id_str] => 542660947589230592 [text] => RT @TrudoLemmens: Inspiring: Child rights activists Malala Yousafzai & Kailash Satyarthi receive joint Nobel award http://example.com [source] => Twitter Web Client [truncated] => [in_reply_to_status_id]
=> [in_reply_to_status_id_str] => [in_reply_to_user_id] => [in_reply_to_user_id_str] => [in_reply_to_screen_name] => [user] => Array ( [id] => 397692076 [id_str] => 397692076 [name] => Vassili Apostol. [screen_name] => v_apostol [location] => Toronto [url] => http://www.apostollaw.ca [description] => Lawyer writer father Ph.D in law candidate @ Osgoode | Health, employment, family, justice, rights, liberties, bioethics, books | I miss swimming in the Aegean [protected] => [verified] => [followers_count] => 200 [friends_count]
=> 304 [listed_count] => 10 [favourites_count] => 17 [statuses_count] => 4290 [created_at] => Tue Oct 25 01:27:15 +0000 2011 [utc_offset] => -18000 [time_zone] => Eastern Time (US & Canada) [geo_enabled] => [lang] => en [contributors_enabled] => [is_translator] => [profile_background_color] => 022330 [profile_background_image_url] => http://abs.twimg.com/images/themes/theme15/bg.png [profile_background_image_url_https] => https://abs.twimg.com/images/themes/theme15/bg.png [profile_background_tile] => [profile_link_color] => 0084B4 [profile_sidebar_border_color] => A8C7F7 [profile_sidebar_fill_color]
=> C0DFEC [profile_text_color] => 333333 [profile_use_background_image] => 1 [profile_image_url] => http://pbs.twimg.com/profile_images/2963256714/99af4a287e550bc804d2689e8cc99ba3_normal.jpeg [profile_image_url_https] => https://pbs.twimg.com/profile_images/2963256714/99af4a287e550bc804d2689e8cc99ba3_normal.jpeg [default_profile] => [default_profile_image] => [following] => [follow_request_sent] => [notifications] => ) [geo] => [coordinates]
=> [place] => [contributors] => [retweeted_status] => Array ( [created_at] => Wed Dec 10 12:41:54 +0000 2014 [id] => 542660477612871680 [id_str] => 542660477612871680 [text] => Inspiring: Child rights activists Malala Yousafzai & Kailash Satyarthi receive joint Nobel award http://example.com [source] => Twitter for Websites [truncated] => [in_reply_to_status_id] => [in_reply_to_status_id_str] => [in_reply_to_user_id] => [in_reply_to_user_id_str] => [in_reply_to_screen_name] => [user] => Array ( [id] => 2440319112 [id_str] => 2440319112 [name] => Trudo Lemmens [screen_name] => TrudoLemmens [location] => Toronto [url] => http://www.law.utoronto.ca/faculty-staff/full-time-faculty/trudo-lemmens [description] => Professor of Law and Bioethics University of Toronto; disillusioned-yet-persistent cyclist in Toronto [protected] => [verified] => [followers_count] => 339 [friends_count] => 264 [listed_count] => 9 [favourites_count] => 6 [statuses_count] => 415 [created_at] => Sat Apr 12 17:32:55 +0000 2014 [utc_offset] => [time_zone] => [geo_enabled] => [lang] => en [contributors_enabled] => [is_translator] => [profile_background_color] => C0DEED [profile_background_image_url] => http://abs.twimg.com/images/themes/theme1/bg.png [profile_background_image_url_https] => https://abs.twimg.com/images/themes/theme1/bg.png [profile_background_tile] => [profile_link_color] => 0084B4 [profile_sidebar_border_color] => C0DEED [profile_sidebar_fill_color]
=> DDEEF6 [profile_text_color] => 333333 [profile_use_background_image] => 1 [profile_image_url] => http://pbs.twimg.com/profile_images/455104260615569408/6OB88Oli_normal.png [profile_image_url_https] => https://pbs.twimg.com/profile_images/455104260615569408/6OB88Oli_normal.png [profile_banner_url] => https://pbs.twimg.com/profile_banners/2440319112/1398742720 [default_profile] => 1 [default_profile_image] => [following] => [follow_request_sent] => [notifications] => ) [geo] => [coordinates]
=> [place] => [contributors] => [retweet_count] => 1 [favorite_count] => 0 [entities] => Array ( [hashtags] => Array ( ) [trends] => Array ( ) [urls] => Array ( [0] => Array ( [url] => http://example.com [expanded_url] => http://www.bbc.com/news/world-asia-30411049 [display_url] => bbc.com/news/world-asi… [indices] => Array ( [0] => 101 [1] => 123 ) ) ) [user_mentions] => Array ( ) [symbols] => Array ( ) ) [favorited] => [retweeted] => [possibly_sensitive] => [filter_level] => low [lang] => en ) [retweet_count] => 0 [favorite_count] => 0 [entities] => Array ( [hashtags] => Array ( ) [trends] => Array ( ) [urls] => Array ( [0] => Array ( [url] => http://example.com [expanded_url] => http://www.bbc.com/news/world-asia-30411049 [display_url] => bbc.com/news/world-asi… [indices] => Array ( [0] => 119 [1] => 141 ) ) ) [user_mentions] => Array ( [0] => Array ( [screen_name] => TrudoLemmens [name] => Trudo Lemmens [id] => 2440319112 [id_str] => 2440319112 [indices] => Array ( [0] => 3 [1] => 16 ) ) ) [symbols] => Array ( ) ) [favorited] => [retweeted] => [possibly_sensitive] => [filter_level] => medium [lang] => en [timestamp_ms] => 1418215426715 ) )
Эта линия — ваша проблема.
//converts json string to an array
$data = json_decode($fetched, true);
Так как $myBucket->get()
вернуть Basho\Riak\Object
,
Тест с этим кодом
// fetches stored raw JSON data from riak database
$fetched = $myBucket->get('542660947589230592');
//get data array
$data = $fetched->getData();
foreach ($data as $tweet) {
echo $tweet['text'];
}
1. Протестируйте / отладьте ваш код и данные
Почему вы думаете, что ваш $fetched
переменная содержит строку JSON? Выход из print_r()
показывает, что это объект (var_dump()
мог бы показать это точно).
2. Проверьте документацию или код библиотеки
От код GitHub:
/**
* Retrieve a JSON-encoded object from Riak.
*
* @param string $key - Name of the key.
* @param int $r - R-Value of the request (defaults to bucket's R)
* @return Object
*/
public function get($key, $r = null)
{
$obj = new Object($this->client, $this, $key);
$obj->jsonize = true;
$r = $this->getR($r);
return $obj->reload($r);
}
ковша get()
метод возвращается с \Basho\Riak\Object
,
Библиотека скрывает протокол на основе JSON и предоставляет проанализированные данные. Вместо json_decode()
, вы должны использовать ->getData()
,