Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php-将字符串拆分为多维数组_Php_Multidimensional Array - Fatal编程技术网

php-将字符串拆分为多维数组

php-将字符串拆分为多维数组,php,multidimensional-array,Php,Multidimensional Array,我正在尝试将导航位置字符串拆分为主数组 例如,如果我有一个项目的位置是1.2.2 我想在主数组中添加它,如下所示 1 => 2 => 2 => array() 然后如果另一个项目有“2.1” 1 => 2 => 2 => array() 2 => 1 => array() 然后是另一个“1.2.3” 1 => 2 => 2 => array

我正在尝试将导航位置字符串拆分为主数组

例如,如果我有一个项目的位置是1.2.2

我想在主数组中添加它,如下所示

 1 =>
    2 =>
        2 => array()
然后如果另一个项目有“2.1”

 1 =>
    2 =>
        2 => array()
 2 =>
    1 => array()
然后是另一个“1.2.3”

 1 =>
    2 =>
        2 => array()
        3 => array()
 2 =>
    1 => array()
有人知道这样做的方法吗

问候

编辑

假设我有一个Objects的一维数组,我想循环遍历它们,并将其存储为一个类似嵌套数组的结构化“导航”。每个项目都有一个导航位置字符串,即1.2.3.6

然后我想到了
$depth=explode('.',$details['navigation\u pos'])通过某种数组遍历器运行它,以将对象放置在正确的位置

希望这有帮助

编辑

也许更好的表达方式是这样,但更优雅:

$depth = explode( '.', '1.2.3.4' );
$bar = json_decode( '{"' . implode( '":{"', $depth ) . '":[]' . str_repeat( '}', sizeof( $depth ) ) );
print_r($bar);
这会给

stdClass Object
(
    [1] => stdClass Object
        (
            [2] => stdClass Object
                (
                    [3] => stdClass Object
                        (
                            [4] => Array
                                (
                                )

                        )

                )

        )

)

您可以使用
eval()
构造,但要注意:

eval()语言构造非常危险,因为它允许执行任意PHP代码。因此,不鼓励使用它。如果您已经仔细验证了除了使用此构造之外没有其他选择,请特别注意,在未事先正确验证的情况下,不要将任何用户提供的数据传递到该构造中


您的输入是什么?是字符串还是数组?输出应该是什么?数组将存储在哪里?在会议中?@Luke Snowden,展示你的确切意图不太确定你的要求是什么。。。位置字符串是一个字符串,即“1.2.3”,我想在该点存储关联项的引用,以便我可以循环遍历它们并显示嵌套导航hmmm,以测试上述内容。设法让它使用以下
$depth=explode('.',$details['navigation\u pos'])$bar=json_decode(“{”.内爆(“:{”,$depth)。“:{”name:“.$details['name'].”,“name:“.$details['name'].'}.”.str_repeat('}',sizeof($depth));$this->navigation=array\u merge\u recursive($this->navigation,(array)$bar);
您也可以尝试对这个问题的公认答案进行调整:(因此它设置了值而不是得到值)好的解决方案Luke,我也遇到了同样的情况。做得好,谢谢!
$final_array = array(); // The output array

/*
    Example:
    $big_array = array(
        '1.1' => 'One-one',
        '2.1.3.4' => 'Two-one-three-four'
    );
*/  

foreach ($big_array as $position_string => $item)
{
    $index_array = explode(".", $position_string);

    foreach ($index_array as $key => $value)
    {       
        // Make sure only integers are put through eval()
        $index_array[$key] = (int)$value;
    }

    $indexes = implode("][", $index_array);

    // TODO: make sure $item is safe to put through eval()!
    eval("\$final_array[{$indexes}] = \$item");
}