我有以下情况:
$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']
}
}
}但没有太多的“如果”,某种递归的东西。
发布于 2015-08-25 20:57:37
您可以使用递归进行此操作,但另一种方法是使用引用。向数组添加一个新级别,然后简单地将引用向下移到该新元素。
<?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);演示:http://codepad.org/f7O0Qy3D
https://stackoverflow.com/questions/32213705
复制相似问题