简体   繁体   English

在PHP中将嵌套(多维)数组更改为键=>值对

[英]Changing a nested (multidimentional) array into key => value pairs in PHP

I have an multidimensional array that looks like this: 我有一个多维数组,看起来像这样:

Array
(
    [0] => Array
        (
            [ClientID] => ec2173de2134fdsfg4fsdffcb4b5205
            [Name] => ABC Widgets
        )

    [1] => Array
        (
            [ClientID] => e5dfgfdg2d760f640aadfgdfgdfg47b
            [Name] => Acme Co
        )

    [2] => Array
        (
            [ClientID] => b9dfgsdfg419085c3sdgffdsgfdg313
            [Name] => 4321 Corp
        )

)

I would like to change to the following: 我想更改为以下内容:

Array
(
  ec2173de2134fdsfg4fsdffcb4b5205 => ABC Widgets
  e5dfgfdg2d760f640aadfgdfgdfg47b => Acme Co
  b9dfgsdfg419085c3sdgffdsgfdg313 => 4321 Corp
)

What is the best way to do so? 最好的方法是什么? Also, would I be better off storing the array in its original format and converting to other formats as needed? 另外,我是否最好将阵列以其原始格式存储并根据需要转换为其他格式? Thank you for any assistance 谢谢您的协助

$flat = array();
foreach($multidim as $item)
    $flat[$item['ClientID']] = $item['Name'];

Whether you'd be better off storing the original form cannot be answered generally. 一般而言,您是否会更好地保存原始表格还是无法解决的。 You should store it if you need it. 如果需要,应该存储它。

It looks like you are creating a hash table with the original data. 似乎您正在使用原始数据创建哈希表。 Hash tables are very fast for accessing and inserting single data elements. 哈希表非常快速地访问和插入单个数据元素。 However, you can't run queries against the data contained in the records--you can only retrieve based on the unique key or insert based on a generated key. 但是,您不能对记录中包含的数据运行查询-您只能基于唯一键进行检索或基于生成的键进行插入。

You might use the original format with all its fields as the "back-end" and generate a hash table like the one you demonstrated. 您可以将原始格式及其所有字段都用作“后端”,并生成一个哈希表,就像您演示的那样。 The draw-back is that every time this table is generated, it costs CPU cycles. 缺点是,每次生成该表时,都会花费CPU周期。

If you throw this data into a database, the DB engine will handle creating regular data tables (like your first one) and hash tables (like your second) as needed for the particular query that you are using. 如果将这些数据放入数据库中,则数据库引擎将根据您所使用的特定查询的需要,来创建常规数据表(如第一个数据表)和哈希表(如第二个数据表)。 You can also force it to create hash tables based on a certain database column. 您也可以强制它基于某个数据库列创建哈希表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM