PHP重命名数组键(不迭代)

时间:2021-11-26 10:45:32

Is it possible to perform changes to the "structure" of an array of associative maps (bulk renaming keys or dropping them entirely) without linearly iterating over the entire array and copying information to a new array? Is there another PHP data structure, like a table or something, that supports this?

是否可以对关联映射数组(批量重命名键或完全丢弃它们)的“结构”进行更改,而无需线性迭代整个数组并将信息复制到新数组?是否有其他PHP数据结构,如表格或其他东西,支持这个?

To make this a bit clearer, can I take this:

为了使这一点更清楚,我可以这样做:

$arr = array(
    array("id" => 1, "something" => "etc"),
    array("id" => 2, "something" => "etc"),
    array("id" => 3, "something" => "etc"),
    array("id" => 4, "something" => "etc"),
    array("id" => 5, "something" => "etc"),
    ...
    array("id" => $over9000, "something" => "etc")
);

and turn it into this:

把它变成这个:

$newarr = array(
    array("id" => 1, "different" => "etc"),
    array("id" => 2, "different" => "etc"),
    array("id" => 3, "different" => "etc"),
    array("id" => 4, "different" => "etc"),
    array("id" => 5, "different" => "etc"),
    ...
    array("id" => $over9000, "different" => "etc")
);

WITHOUT doing this:

没有这样做:

$newarr = array_map(function($i){
    return array(
        "id" => $i["id"], 
        "different" => $i["something"]
    );
}, $arr);

My use case is getting about 70,000 rows from an SQL database in some format I can't control, and having to serialize it to JSON a particular way (the keys are differently named). It seems like a huge waste of 10 to 15 seconds to just loop through the array of all the record objects returned and perform the same selective copying operation on each one.

我的用例是以某种我无法控制的格式从SQL数据库获取大约70,000行,并且必须以特定方式将其序列化为JSON(键的名称不同)。只需循环返回所有返回的记录对象的数组并在每个记录对象上执行相同的选择性复制操作,这似乎是浪费10到15秒的巨大浪费。

Is there a way to do this in constant time? I'm interfacing with the PHPADODb to get stuff from the database, so if it already has some structure like this which separates schema from data that would be perfect.

有没有办法在恒定的时间内做到这一点?我正在与PHPADODb接口以从数据库中获取内容,因此如果它已经有一些像这样的结构,它将模式与完美的数据分开。

1 个解决方案

#1


0  

Is there a way to do this in constant time?

有没有办法在恒定的时间内做到这一点?

There is no way to do that. The items in an array are independent, so there is just no way to change their structure in a constant time.

没有办法做到这一点。数组中的项是独立的,因此无法在恒定时间内更改其结构。

#1


0  

Is there a way to do this in constant time?

有没有办法在恒定的时间内做到这一点?

There is no way to do that. The items in an array are independent, so there is just no way to change their structure in a constant time.

没有办法做到这一点。数组中的项是独立的,因此无法在恒定时间内更改其结构。