2016-05-31 3 views
-1

배열에서 "replaceMe"및 "replaceMeToo"라는 이름의 모든 필드를 대체하는 방법은 무엇입니까? stackoverflow에 비슷한 질문이 있다는 것을 알고 있지만 아무도 나를 정말로 도왔습니다.PHP에서 연관 배열의 일부 필드를 바꾸는 방법은 무엇입니까?

$ array -> loadObjectList()에서 $ array가 반환됩니다. Joomla. $ 배열의

예 위해서 var_dump :

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

감사 : 결과는 같아야합니다

// @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) "48" 
    ["replaceMeToo"]=> 
    string(2) "53" 
    } 
    [1]=> 
    object(stdClass)#119 (14) { 
    ["id"]=> 
    string(1) "1" 
    ["replaceMe"]=> 
    string(2) "5555" 
    ["replaceMeToo"]=> 
    string(2) "5555" 
    } 
} 

내가 좋아하는 일을하고 싶습니다.

+1

당신이 결과에 싶어. 대체 후 얻을 결과 배열을 사용하여 질문을 완료 할 수 있습니까? – Taras

+0

좋아요, 결과에 대한 예제를 추가했습니다. –

답변

0

foreach($array as $arr){ 

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

} 
+0

설명을 추가해주세요. – Trix

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)); 
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   
) 
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); 
관련 문제