user657821
user657821

Reputation: 1017

changing keys of a multidimensional array

I have a multidimensional array as shown below. How do I change the keys that start with "id of"?

Array
(
[0] => Array
    (
        [id of ten] => 1871
        [name] => bob
    )

[1] => Array
    (
        [id of nine hundred thousand] => 12581
        [name] => barney        
    )

)

Normally, you'd do something like:

foreach ( $array as $k=>$v )
{
  $array[$k] ['id'] = $array[$k] ['old'];
  unset($array[$k]['old']);
}

In my case, the key changes dynamically (there are thousands of keys in my multidimensional array and they are random but they will always start w/ "id of...")

thx!

Upvotes: 3

Views: 1691

Answers (3)

de3
de3

Reputation: 2000

This solution is very clean. Array_shift, does two things at once: returns first element (which has the id), and deletes it from the array, so you can directly assign it to the $new_array at 'id'

$new_arr=array();
foreach ( $array as $arr)
{
  $new_arr[array_shift($arr)] = $arr;
}

Upvotes: 2

Jared Farrish
Jared Farrish

Reputation: 49188

I'm wondering if this is what you are looking for:

<?php

$array = array(
    array(
        "id of one" => 434,
        "name" => "bob"
    ),
    array(
        "id of two" => 9323,
        "name" => "ted"
    )
);

$c_array = count($array);

for ($i = 0; $i < $c_array; $i++)
{
    foreach ($array[$i] as $key => $value)
    {
        if (substr($key, 0, 5) == 'id of') {
            $array[$i][substr($key, 6)] = $value;
            unset($array[$i][$key]);
        }
    }
}

print_r($array);

?>

NOTE: Includes use of substr() instead of strpos(). See Gumbo's comment below.

https://ideone.com/xBV5L

This outputs:

Array
(
    [0] => Array
        (
            [name] => bob
            [one] => 434
        )

    [1] => Array
        (
            [name] => ted
            [two] => 9323
        )

)

Upvotes: 2

davishmcclurg
davishmcclurg

Reputation: 419

If the 'id of' key is always the first element of the array, you can use the following:

foreach ($input as &$value)
{
  $value['key'] = reset($value);
  $key = key($value);
  unset($value[$key]);
}

Otherwise, the following worked for me:

foreach ($input as &$value)
{
  foreach ($value as $key=>$el) {
    if (substr($key, 0, 5) == 'id of') {
      $value['key'] = $el;
      unset($value[$key]);
    }
  }
}

In both cases you can change $value['key'] to whatever you want the new key to be.

Upvotes: 1

Related Questions