【问题标题】:PHP process array into var - keyPHP进程数组转换成var-key
【发布时间】:2018-05-22 13:42:20
【问题描述】:

我有一个数组,我正在尝试找出如何循环遍历它,将键分配为 php 变量,将值分配为 php 值。

Array
(
    [count] => 1
    [0] => Array
        (
            [cn] => Array
                (
                    [count] => 1
                    [0] => Distributed Site
                )

            [0] => cn
            [description] => Array
                (
                    [count] => 1
                    [0] => Multisite Location
                )

            [1] => description
            [location] => Array
                (
                    [count] => 1
                    [0] => b0e81b22-4448-48d2-b641-515b6d4f38d7
                )

            [2] => location
            [owner] => Array
                (
                    [count] => 1
                    [0] => ec19c2db-25ec-4e89-8143-8864417e4f23
                )

            [3] => owner
            [count] => 4
            [dn] => cn=Distributed Site,cn=Local,cn=Sites
        )

)

所以我最终会得到

$cn with a value of 'Distrusted Site'
$description with a value of 'Multisite Location'
$location with a value of 'b0e81b22-4448-48d2-b641-515b6d4f38d7'

等等。

知道怎么做吗?

谢谢

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 我认为您更多的是在问“我应该构建什么源数组来以一种我可以有效访问/操作的方式为我提供我想要的数据”?我无法理解你是如何得到如此混乱的数据数组的。你是从哪里弄来的?
  • 牢记以下引用:如果 eval() 是答案,那么您几乎肯定是在问错误的问题。 -- Rasmus Lerdorf,PHP 的 BDFL

标签: php arrays variables


【解决方案1】:

您需要调整您的数据结构以唯一地使用变量名一次且仅一次:

foreach($array as $key=>$value){
    ${$key} = $value;
}

这是非常不鼓励的,因为它忽略了使用数组的 PHP 基础知识,但这可以满足您的需求。

【讨论】:

    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2011-11-15
    相关资源
    最近更新 更多