2017-02-23 38 views
1

我有一個看起來像JSON響應這個在陣列替換字符串的一部分PHP

(
    [0] => stdClass Object 

    (
     [default] => false 
     [loc] => http://somethingirrelevant.lol 
     [temp] => '100' 
    ) 

) 

什麼,我希望完成在[LOC]的URL更改爲https

我試着使用:

$array = preg_replace('http','https' $array); 

但完全破壞數組!

+0

你給向上? – AbraCadaver

回答

0

你不能簡單地調用數組,你可以做的是迭代throught它和替換的關鍵loc每個值:

foreach($array AS $key=>$value) { 
    if(isset($value['LOC'])) { 
     $array[$key]['LOC'] = preg_replace('http','https', $array); 
    } 
} 

你可以投你數組的規則陣列,而不是一個對象:

if(!is_array($array)) $array = (array)array; 
+0

你試過了嗎? ==>'語法錯誤' – Toto

+0

實際上,語法錯誤是在我複製的原始代碼中,但我應該注意到它。謝謝。 – Nicolas

1

您有一個對象數組。數組鍵0是一個loc屬性的對象,你可以在這裏使用str_replace()

$array[0]->loc = str_replace('http://', 'https://', $array[0]->loc); 
//$array[0]->loc = preg_replace('#http://#', 'https://', $array[0]->loc); 

如果解碼作爲數組:

$array = json_decode($json, true); 

然後:

$array[0]['loc'] = str_replace('http://', 'https://', $array[0]['loc']); 
+0

你試過了嗎? ==>'語法錯誤' – Toto

+0

不僅如此,正則表達式必須包含在分隔符之間;) – Toto

+0

我會添加你應該使用wordboundary來避免用'httpss'替換'https' – Toto