Briggz
Briggz

Reputation: 3

PHP array replace key names only

I have an array that I am retrieving from an alternative source, the keys are preset strings. I'm using $devices as an example of the array that I would retrieve.

I want to replace the key names of $devices with 1 to 1 match of $new_keys. Below code is what I have so far but I'm not getting the result I am looking for?

$devices = array('uniqueId' => '1234','status' => 'online','lastUpdate' => time(),'phone' => '1234','model' => 'test','contact' => 'admin'
$new_keys = array('IMEI','Status','Last Update','Phone','Model','Contact');            

for ($i = 0; $i < count($devices) - 1; $i++) {
    array_replace($devices[$i], $new_keys[$i]);
}

Thanks!

Upvotes: 0

Views: 284

Answers (4)

Rahul
Rahul

Reputation: 18557

try this,

$arr = array_combine($new_keys,$devices);
print_r($arr);

Here is the source which states Creates an array by using one array for keys and another for its values

Upvotes: 0

Tom
Tom

Reputation: 4292

array_replace will replace the values where the keys match, not the keys themselves.

You're probably best creating a new array and merging the two in your loop. You need to swap aout for for foreach, and you also can't reference (I don't think) your $devices array with $i.

$devices = array('uniqueId' => '1234','status' => 'online','lastUpdate' => time(),'phone' => '1234','model' => 'test','contact' => 'admin'
$new_keys = array('IMEI','Status','Last Update','Phone','Model','Contact');            
$new_devices = array();

$i = 0;
foreach($devices as $key => $value) {
    $new_devices[$new_keys[$i]] = $value;
    $i++;
}

I'm not sure what you're actually doing here, but using this 1-to-1 relationship of old and new keys, based on their position, is asking for trouble!

Upvotes: 1

axiac
axiac

Reputation: 72226

Take a look at PHP function array_combine(). It does what you need:

$devices = array('uniqueId' => '1234','status' => 'online','lastUpdate' => time(),'phone' => '1234','model' => 'test','contact' => 'admin');
$new_keys = array('IMEI','Status','Last Update','Phone','Model','Contact');            

$fixed = array_combine($new_keys, array_values($devices));

// print_r($fixed);

The output:

Array
(
    [IMEI] => 1234
    [Status] => online
    [Last Update] => 1490179692
    [Phone] => 1234
    [Model] => test
    [Contact] => admin
)

Upvotes: 3

Maciej__
Maciej__

Reputation: 149

$newArr = array();
for ($i = 0; $i < count($devices) - 1; $i++) {
$newArr[$new_keys[$i]]=$devices[$i];
}
$device = $newArr;

Upvotes: 0

Related Questions