dongshukou0240
2018-03-17 20:25
浏览 59
已采纳

PHP递归练习构建数组

[
    'one/two' => 3,
    'one/four/0' => 5,
    'one/four/1' => 6,
    'one/four/2' => 7,
    'eight/nine/ten' => 11
]

I am attempting to build the above array based on $json_str:

$json_str = '{
    "one":
    {
        "two": 3,
        "four": [ 5,6,7]
    },
    "eight":
    {
        "nine":
        {
            "ten":11
        }
    }
}';

I built a recursive function that loops thru this $json_str but so far I can only get strings to output.

How would I build an array instead echoing a string?

Also, how would I get only index values that belong in the associative index to be there.

Currently I can only get all keys to print:

one/two => 3

one/two/four/0 => 5

one/two/four/0/1 => 6

one/two/four/0/1/2 => 7

one/eight/nine/ten => 11

Below is what I have so far:

<?php

function printAll($a, $prefix = '') {

  if (!is_array($a) && !is_object($a)) {

    $prefix = rtrim($prefix, '/');

    echo $prefix . ' => ' . $a, "
";

    return;
  }

  foreach($a as $k => $v) {

    $prefix .= $k . "/";

    printAll($v, $prefix);
  }
}


$json_str = '{
                "one":
                {
                    "two": 3,
                    "four": [ 5,6,7]
                },
                "eight":
                {
                    "nine":
                    {
                        "ten":11
                    }
                }
            }';


$object = json_decode($json_str);
printAll($object);

图片转代码服务由CSDN问答提供 功能建议

  [
'one / two'=&gt;  3,
'one / four / 0'=&gt;  5,
'one / four / 1'=&gt;  6,
'one / four / 2'=&gt;  7,
'八/九/十'=&gt;  11 
] 
   
 
 

我正在尝试基于$ json_str构建上述数组:

  $ json_str  ='{
“one”:
 {
“两个”:3,
“四”:[5,6,7] 
},
“八”:
 {
“九 “:
 {
”“十”:11 
} 
} 
}'; 
   
 
 

我构建了一个递归函数,通过这个$循环 json_str但到目前为止我只能输出字符串。

我如何构建一个数组而不是回显一个字符串?

另外,我怎么办? 只获取属于关联索引的索引值。

目前我只能获取所有要打印的键:

  one  / two =&gt;  3 
 
one / two / four / 0 =&gt;  5 
 
one / two / four / 0/1 =&gt;  6 
 
one / two / four / 0/1/2 =&gt;  7 
 
one / eight / nine / ten =&gt;  11 
   
 
 

以下是我到目前为止的内容:

 &lt;?  php 
 
 function printAll($ a,$ prefix =''){
 
 if if(!is_array($ a)&amp;&amp;!is_object($ a)){
 
 $ prefix = rtrim(  $ prefix,'/'); 
 
 echo $ prefix。  '=&gt;  '。  $ a,“
”; 
 
返回; 
} 
 
 foreach($ a as $ k =&gt; $ v){
 
 $前缀。= $ k。  “/”; 
 
 printAll($ v,$ prefix); 
} 
} 
 
 
 $ json_str ='{
“one”:
 {
“two”:3  ,
“四”:[5,6,7] 
},
“八”:
 {
“九”:
 {
“十”:11 
} 
} \  n}'; 
 
 
 $ object = json_decode($ json_str); 
printAll($ object); 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题