A...">

Change multidimensional array keys

I have a multidimensional array as shown below. How to change keys starting with "id of"?

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

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

)

Usually you 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 run w / "id of ...")

THX!

+3
source share
3 answers

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 what you want the new key to be.

+1
source

I wonder, 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);

?>

. substr() strpos(). . Gumbo .

https://ideone.com/xBV5L

:

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

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

)
+2

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

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

All Articles