Answer the question
In order to leave comments, you need to log in
How to traverse JSON recursively?
I'm trying to parse a bookmark file from Google Chrome. As you know, this is just a JSON file. And here's something stuck on the recursion. Displays an empty table and at least crack. Where did I screw up?
// читаем файл с закладками в формате JSON
$str = file_get_contents('Bookmarks');
$ar = json_decode($str);
$chld = $ar->roots->other->children;
$marks = array();
function recursiveJSON2ARRAY($obj, $arr){
foreach($obj as $v){
if(isset($v->children) && is_array($v->children) && count($v->children) > 0){
foreach($v->children as $child){
if(isset($child->url)){
$arr[$child->date_added] = array('name'=>$child->name, 'url'=>$child->url);
}
else{
recursiveJSON2ARRAY($child, $arr);
}
}
}
else{
if(isset($v->url)){
$arr[$v->date_added] = array('name'=>$v->name, 'url'=>$v->url);
}
}
}
}
recursiveJSON2ARRAY($chld, $marks);
//krsort($marks); // Reverse sort the bookmarks by date added
$table = '<table cellspacing="2" cellpadding="2" border="1" width="600"><tr><td><b>Date</b></td><td><b>Name</b></td><td><b>URL</b></td></tr>';
foreach($marks as $date=>$mark)
{
$table .= '<tr><td>'.date('H:m:s d-m-Y', $date).'</td><td>'.$mark['name'].'</td><td><a href="'.$mark['url'].'" target="_blank">'.$mark['url'].'</a></td></tr>';
}
$table .= '</table>';
echo $table;
Answer the question
In order to leave comments, you need to log in
$ar = json_decode($str, TRUE); // will return an array. php.net/manual/en/function.json-decode.php
$names= array_column($ar, 'name'); // recursively find "name" php.net/manual/en/function.array-column.php
Madridian Fox is right.
Do it like thisfunction recursiveJSON2ARRAY($obj, &$arr){
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$file = '/path/to/file';
$array = json_decode(file_get_contents($file), true);
function buildBookmarks($bookmarks, $name, &$output = [])
{
if (!isset($bookmarks['children'])) {
$output[$name][] = $bookmarks;
return;
}
foreach ($bookmarks['children'] as $child) {
if ($bookmark = buildBookmarks($child, $array['name'], $output)) {
$output[$name][] = $bookmark;
}
}
}
buildBookmarks($array['roots']['bookmark_bar'], 'root', $bookmarks);
foreach ($bookmarks as $folder => $children) {
foreach ($children as $bookmark) {
echo "<pre>";
var_dump($folder, $bookmark);
echo "</pre>";
exit("File: " . __FILE__ . " Line: " . __LINE__);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question