在多维数组PHP str_replace转换键 [英] str_replace keys in multidimensional array PHP

查看:207
本文介绍了在多维数组PHP str_replace转换键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组如下所示:

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

我想循环数组和替换OBJECT_ID键NEW_ID使用str_replace函数。

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
     }
    }
  }

以上code不起作用,你可以看到我在做什么错了?
我试着用字符串,而不是变量,但也不能工作。
先谢谢了。

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.

推荐答案

...如果你真的想用 str_replace()函数

...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)

这篇关于在多维数组PHP str_replace转换键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆