如何在PHP中替换关联数组的某些字段?

时间:2016-05-31 16:13:05

标签: php arrays associative-array

如何替换名为" replaceMe"的所有字段?和" replaceMeToo"在一个数组?我知道stackoverflow上有类似的问题,但没有人真正帮助过我。

$ array从$ db-> loadObjectList()返回;在Joomla。

$ array的var_dump示例:

array(2) {
  [0]=>
  object(stdClass)#118 (14) {
    ["id"]=>
    string(1) "1"
    ["replaceMe"]=>
    string(2) "48"
    ["replaceMeToo"]=>
    string(2) "53"
  }
  [1]=>
  object(stdClass)#119 (14) {
    ["id"]=>
    string(1) "1"
    ["replaceMe"]=>
    string(2) "5555"
    ["replaceMeToo"]=>
    string(2) "5555"
  }
}

我想做类似的事情:

// @param int, @return string
$array['replaceMe'] = doSomething($array['replaceMe']);
$array['replaceMeToo'] = doSomething($array['replaceMeToo']);

结果如下:

array(2) {
  [0]=>
  object(stdClass)#118 (14) {
    ["id"]=>
    string(1) "1"
    ["replaceMe"]=>
    string(2) "I was replaced by a value from db #1"
    ["replaceMeToo"]=>
    string(2) "I was replaced by a value from db #2"
  }
  [1]=>
  object(stdClass)#119 (14) {
    ["id"]=>
    string(1) "1"
    ["replaceMe"]=>
    string(2) "I was replaced by a value from db #3"
    ["replaceMeToo"]=>
    string(2) "I was replaced by a value from db #4"
  }
}

感谢。

4 个答案:

答案 0 :(得分:0)

尝试

foreach($array as $arr){

  $arr->replaceMeToo = $arr->replaceMe;
  unset($arr->replaceMe);

}

答案 1 :(得分:0)

尝试使用str_replace,示例代码:

使用循环:

foreach ($array as &$new) {
  $new = str_replace('replaceMe', 'replacedYou', str_replace('replaceMeToo', 'replacedYouTo', $new));
}

没有循环:

$new = str_replace('replaceMe', 'replacedYou', str_replace('replaceMeToo', 'replacedYouTo', $array));

答案 2 :(得分:0)

您可以使用array_replace

实施例

$yourArray = array("id","replaceMe","replaceMeToo");
$replaceMentArray = array(1 => "db1", 2 => "db2");
$newArray = array_replace($yourArray,$replaceMentArray);

输出

Array
(
    [0] => id
    [1] => db1
    [2] => db2        
)

答案 3 :(得分:0)

感谢所有答案。你帮了我!每个人都会投票。

我解决了这个问题:

        $result = $db->loadObjectList();

        $newArray = array();
        foreach ($result as $row) {
            $tempArray = array(
                'id' => $row->id,
                'published' => $row->published,
                'date' => $row->date,
                'hours' => $row->hours,
                'class' => $row->class,
                'type' => $row->type,
                'subject' => $row->subject,
                'subject_sub' => $row->subject_sub,
                'teacher' => JFactory::getUser($row->teacher)->name, //replace userId with name
                'teacher_sub' => JFactory::getUser($row->teacher_sub)->name, // replace userId with name
                'room' => $row->room,
                'comment' => $row->comment,
                'created' => $row->created,
                'modified' => $row->modified
            );
            array_push($newArray, $tempArray);
        }

        echo json_encode($newArray, JSON_FORCE_OBJECT);