-->

str_replace keys in multidimensional array PHP

2019-07-21 07:02发布

问题:

I have a multidimensional array like the following:

Array (
    [results] => Array (
        [0] => Array (
            [object_id] => 13
            [id] => 13
            [idno] => e00110-o00005-2010-PROG
            [display_label] => La Bohème / PUCCINI - 2010
            [ca_objects.description] => Libreto de Luigi Illica y Giuseppe Giacosa basado en Escenas de la vida bohemia de Henri Murger Nueva producción – Teatro Colón
            [ca_objects.type_id] => Programa de mano
        )
        //more data here

I'm trying to loop the array and replace "object_id" key for "new_id" using str_replace.

$str="object_id";//The string to search for

$rep="new_id";//The replacement string


foreach ($array as $value) {
   foreach ($value as $key2 => $value2) {
     foreach ($value2 as $key3 => $value3) {
      str_replace($str,$rep,$key3);
       echo $key3." : ".$value3."<br>"; //It gets printed with no changes
     }
    }
  }

The above code does not work, can you see what am I doing wrong?. I tried using strings instead of variables but didn't work either. Thanks in advance.

回答1:

...if you really want to use str_replace():

$array['results'] = array_map(function($item){
  $keys = implode(',', array_keys($item));
  $keys = str_replace('object_id', 'new_id', $keys);
  return array_combine(explode(',', $keys), array_values($item));

}, $array['results']);

The other way - create a new array, then iterate over the old array and assign values from it to the new array, while changing the keys you want:

$array['results'] = array_map(function($item){
  $item['new_id'] = $item['object_id'];      
  unset($item['object_id']);
  return $item;

}, $array['results']);

(this one will reorder the array, if it matters)



回答2:

foreach ($array as &$value) {
  foreach ($value as $key2 => &$value2) {
    $value2[$rep] = $value2[$str];
    unset($value2[$str]);
  }
}

It's necessary to iterate over the arrays using references so that the modifications affect the original array, not a copy.



回答3:

@One Trick Pony: I followed your suggestion and created a new array. It was exactly what I needed and I did it by myself!!. Following code creates the new array. Thank you all so much for helping me!

 $display=array();
    foreach ($array as $value) {
      foreach ($value as $value2) {
        $display [] = array (
                         'Id del objeto' => $value2['object_id'],
                         'Título' => $value2['display_label'],
                         'Descripción' => $value2['ca_objects.description'],
                         );
              }
    }