Question

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?

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.

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top