JSON, or JavaScript Object Notation, is fairly popular.
This is just my modest take on a ‘PHP Object Notation’ implementation.
Note that it is meant to follow how your mind works rather than being syntactically correct; therefore, associative arrays are used in a loose manner where you have to worry about associative syntax as little as possible.
Basically, type away until your object is fully described.
Here is a notation sample:
.
This syntax can then be used the same way JSON is used, using eval. Here is how and you will immediately notice how the eval() syntax has to differ from the JavaScript one:
.
Feels a bit clumsy. Fortunately, starting with PHP4, if you are not too sad about introducing a statement in your remote string, you can rewrite it like this:
.
Better, isn’t it?
In this last listing, you will find the very simple code I wrote to traverse the object. Note that I invoke a callback for every element, otherwise this code would not be very helpful.
Note that this is just a concept for something I needed to throw together quickly therefore there are some limitations; for instance, you cannot have numeric keys since in this context their “keyness” is ignored and even feared.
-
<?php
-
function traverse_tree($callback, $curlevel, $curdepth, $uid)
-
{
-
$depthstr = ‘——————————————————————————’;
-
{
-
$callback($curlevel, $padding, $uid);
-
return;
-
}
-
foreach($curlevel as $level=>$children)
-
{
-
{
-
$my_uid = $callback($level, $padding, $uid);
-
traverse_tree($callback, $children, $curdepth + 2, $my_uid);
-
}
-
else
-
{
-
$callback($children, $padding, $uid);
-
}
-
}
-
}
-
-
function do_something($name, $padding, $uid)
-
{
-
$iid = 0; // Bogus value
-
return $iid;
-
}
-
-
// ———————————————————–
-
// Here we go
-
// ———————————————————–
-
$rootnodename = &$argv[1];
-
-
‘Yamaha’ => ‘Fz’,
-
‘Honda’,
-
‘Norton’
-
),
-
‘Trikes’,
-
‘Camaro’,
-
‘Jimmy’
-
),
-
‘Explorer’,
-
‘Crown Victoria’
-
),
-
‘Dodge’ => ‘Charger’,
-
‘300X’,
-
‘Le Baron’
-
),
-
)
-
)
-
);
-
-
traverse_tree(do_something, $INS, 0, 1);
-
-
print "DONE\n\n";
-
?>
.
Invoke with:
-
php my_php_script.php "Vehicles"
.
“What is this $iid variable?” you may ask.
You will notice that this piece of code is particularly convenient if you want to add a whole tree structure to your database. Say the you are using MySQL and want to create categories and sub-categories, using the column ‘pid’ as a category’s parent id. You would rewrite do_something:
-
function do_something($name, $padding, $uid)
-
{
-
return $iid;
-
}
Voila!
Sphere: Related Content
[…] 「evalしてJavascriptオブジェクトになるデータ形式がJSONなんだろ、そんなのPHPでもできるぜ!」ということでPON(PHP Object Notation)です。 […]
thats it, guy