[英]PHP parse json_decode array
I have a json_array - $json_array
which is multi-level the code below "spits it" out correctly but is there a better way of doing it?我有一个 json_array -
$json_array
它是多级的,下面的代码正确“吐出”但是有更好的方法吗? What I will end up with is a structured XML document with the array keys as the element names - but they must be in the same format as the json array:我最终会得到一个结构化的 XML 文档,其中数组键作为元素名称 - 但它们必须与 json 数组的格式相同:
eg例如
[1] => stdClass Object (
[content] => stdClass Object ( array )
[general] => stdClass Object ( array )
[costing] => stdClass Object ( array )
[socialbits] => stdClass Object (array )
[options] => stdClass Object ( (array)
( [0] => stdClass Object ( array(array) ) ) ) )
Where 1 is the main array key (actually the id from a database)其中 1 是主数组键(实际上是数据库中的 id)
$json_array = json_encode($data);
foreach(json_decode($json_array) as $k=>$val) {
foreach($val as $k1=>$v2){
echo $k1;
echo '<br />';
foreach($v2 as $k3=>$v3){
echo $k3;
echo '<br />';
if(is_array($v3)){
foreach($v3 as $k4=>$v4){
foreach($v4 as $k5=>$v5){
echo $k5;
echo '<br />';
foreach($v5 as $k6=>$v6){
echo $v6;
echo '<br />'
}
}
}
}
echo $v3;
}
echo '<br />';
}
echo '<br />';
}
// } OP included the closing brace.
Thoughts and ideas most welcome thanks -最欢迎的想法和想法谢谢 -
EDIT编辑
I have no objection to edits of code, but for the sake of others please make sure they are accurate.我不反对修改代码,但为了他人着想,请确保它们是准确的。 This is a corrected form of the edit;
这是编辑的更正形式;
foreach(json_decode($json_array) as $k=>$val) {
foreach($val as $k1=>$v2){
echo $k1;
echo '<br />';
foreach($v2 as $k3=>$v3){
echo $k3;
echo '<br />';
if(is_array($v3)){
foreach($v3 as $k4=>$v4){
foreach($v4 as $k5=>$v5){
echo $k5;
echo '<br />';
foreach($v5 as $k6=>$v6){
echo $v6;
echo '<br />';
}
}
}
} else {
echo $v3;
}
}
echo '<br />';
}
echo '<br />';
}
I think this may help you achieve an xml representation of json which is what I assume you require from reading your question:我认为这可能会帮助您实现 json 的 xml 表示,这是我假设您在阅读您的问题时需要的:
<?php
echo recurseJson2XML($json_array, true);
function recurseJson2XML($json, $root = false)
{
$element = '';
foreach($json as $key => $value)
{
if(is_numeric($key))
{
$key = 'element_' . $key;
}
$element .= "<{$key}>";
if(is_array($value) || is_object($value))
{
$element .= recurseJson2XML($value);
}
else
{
$element .= $value;
}
$element .= "</{$key}>";
}
if($root)
{
$element = "<?xml version=\"1.0\" ?><root>{$element}</root>";
}
return $element;
}
?>
I tested to make sure it works on a json decoded string and it works... Let me know if you have any issues.我进行了测试以确保它可以在 json 解码的字符串上工作并且它可以工作......如果您有任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.