- 文字列のエコー関数内から:(Demo) $array=json_decode('{
"Group1": {
"Blue": {
"Round": {
"One": [
"Lawrence",
"Anant",
"B."
],
"Two": [
"Erwin"
]
}
},
"Green": [
"Bryan",
"Mick"
]
},
"Group2": [
"Peter",
"Kris"
]
}', true);
function recurse($array,$path=''){
foreach($array as $k=>$v){
if(!is_array(current($v))){ // check type of the first sub-element's value
echo ($path?"$path > ":''),"$k > (".implode(', ',$v).")\n"; // don't recurse, just implode the indexed elements
}else{ // recurse because at least 2 levels below
recurse($v,($path?"$path > $k":$k)); // build path appropriately
}
}
}
recurse($array);
出力:
Group1 > Blue > Round > One > (Lawrence, Anant, B.)
Group1 > Blue > Round > Two > (Erwin)
Group1 > Green > (Bryan, Mick)
Group2 > (Peter, Kris)
方法#2 - パスの4要素の配列を返す:(Demo)
function recurse($array,$path='',&$result=[]){
foreach($array as $k=>$v){
if(!is_array(current($v))){ // check type of the first sub-element's value
$result[]=($path?"$path > ":'')."$k > (".implode(', ',$v).')'; // don't recurse, just implode the indexed elements
}else{ // recurse because at least 2 levels below
recurse($v,($path?"$path > ":'').$k,$result); // build path appropriately
}
}
return $result;
}
var_export(recurse($array));
出力:
array (
0 => 'Group1 > Blue > Round > One > (Lawrence, Anant, B.)',
1 => 'Group1 > Blue > Round > Two > (Erwin)',
2 => 'Group1 > Green > (Bryan, Mick)',
3 => 'Group2 > (Peter, Kris)',
)
そして1つの最終アップデート:
私が与えることができる最高のアドバイスは、この中間のステップを切り出し、ちょうど(再帰なし/必須積み重ねない)新しい所望の出力にyour raw/initial json stringを変換するために、次のようになります。
コード:(Demo)
$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Lawrence" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Anant" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "B." },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Two", "tier5": "Erwin" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Bryan" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Mick" },
{ "tier1": "Group2", "tier2": "Peter" },
{ "tier1": "Group2", "tier2": "Kris" }]',true);
foreach($seperateArray as $row){
$last_val=current(array_splice($row,-1)); // extract last element, store as string
$results[implode(' > ',$row)][]=$last_val;
}
foreach($results as $k=>$v){
echo "$k > (",implode(', ',$v),")\n";
}
// same output as earlier methods
あなたは各メンバーを通過する必要がありますか?多分 'array_walk' – Erwin
Yeaのようなものがほしいと思うかもしれません。うーん、深い配列でどう動くかわからないけど、それを試してみるよ – bryan
あなたのオブジェクトは常に 'Group> Color> Shapes> Names'の形式ですか?あるいは、追加のカテゴリや何かが存在する可能性がありますか? – Erwin