我有以下情况:
$class = 'Main\Entity\Redaction'; #or anything else namespaced class
$nameClass = explode('\\', $class);
$jsonNamespace = [];
if (!empty($nameClass[0])) {
$jsonNamespace[$nameClass[0]] = [];
if (!empty($nameClass[1])) {
$jsonNamespace[$nameClass[0]][$nameClass[1]] = [];
if (!empty($nameClass[2])) {
$jsonNamespace[$nameClass[0]][$nameClass[1]][$nameClass[2]] = ['#wherever'];
}
}
}
我想声明一个名称空间对象JSON。 像这样:
{
Main: {
Entity: {
Redaction: ['#wherever']
}
}
}
但是没有很多" IF&#34 ;,递归的东西。 有什么想法吗?
PS:对不起主持人,我不知道怎么问这个。请帮我改进我的问题。
答案 0 :(得分:1)
您可以使用递归执行此操作,但另一种方法是使用引用。向数组添加一个新级别,然后只需将引用向下移动到该新元素。
<?php
function buildArray(array $keys, $value){
$ret = array();
$ref =& $ret;
foreach($keys as $key){
// Add the next level to the array
$ref[$key] = array();
// Then shift the reference, so that the next
// iteration can add a new level
$ref =& $ref[$key];
}
// $ref is a reference to the lowest level added
$ref = array($value);
// Not totally sure if this is needed
unset($ref);
return $ret;
}
$class = 'Main\Entity\Redaction';
$jsonNamespace = buildArray(explode('\\', $class), array('#wherever'));
var_dump($jsonNamespace);