我得到了一个叫做水果的数组。在这个数组中,如果我有oranges
,我将其更改为I like
,然后其他任何橙色都将使用递归函数更改值。
到目前为止,我已经提出了这个=>
$fruits = array("apple", "orange", "apple", "orange", "watermelon", "orange");
foreach($fruits as $key=>$fruit){
if($fruit == "orange"){
$fruits[$key] = "I like";
$fruits = rec_fruits($fruits, 0);
}
}
function rec_fruits($arr, $i){
if(count($arr) > $i ) {
if($arr[$i] == "orange" ){
$arr[$i] = "grape";
}
$i++;
return rec_fruits($arr, $i );
} else {
return $arr;
}
}
这不会对$fruits
数组进行任何更改。即使使用这样的递归函数,$fruits
=>
function rec_fruits(&$arr, $i)
在foreach中使用而不将其分配给$fruits
数组=>
rec_fruits($fruits, 0);
我知道有多种方法可以实现,但是我想这样做。
我想要数组中的最终像这样=>
数组(
[0] =>苹果
[1] =>我喜欢
[2] =>苹果
[3] =>葡萄
[4] =>西瓜
[5] =>葡萄)
答案 0 :(得分:1)
不确定要完成什么。但是,在调用rec_fruits
时,count($arr) > $i
不会返回任何内容,因此您将null
返回到fruits
,这会导致未定义索引的出现。
function rec_fruits($arr, $i){
if(count($arr) > $i ) {
if($arr[$i] == "orange" ){
$arr[$i] = "grape";
}
$i++;
return rec_fruits($arr, $i );
} else {
return $arr;
}
}
答案 1 :(得分:1)
好吧,如果您一直想知道为什么对Array
不做任何更改,那是因为以下几行:
$fruits = array("apple", "orange", "apple", "orange", "watermelon", "orange");
// Note: Your above array is not an associative array which contains Key-Value pairs
// But here in the bellow foreach-loop you are trying to instantiate a Key-Value
// pair for each of the element in the given array
foreach($fruits as $key=>$fruit){
// So it doesn't even touch following lines and it doesn't go for the recursive function call too :D
if($fruit == "orange"){
$fruits[$key] = "I like";
$fruits = rec_fruits($fruits, 0);
}
}
所以我所做的一切都是为了减轻痛苦,我用传统的老式for循环代替了foreach循环。现在代码如下,每个人都很高兴:
<?php
$fruits = array("apple", "orange", "apple", "orange", "watermelon", "orange");
for($i = 0; count($fruits) > $i; $i++){
if($fruits[$i] == "orange"){
$fruits[$i] = "I like";
$fruits = rec_fruits($fruits, 0);
}
}
echo json_encode($fruits);
function rec_fruits($arr, $i){
if(count($arr) > $i ) {
if($arr[$i] == "orange" ){
$arr[$i] = "grape";
}
$i++;
return rec_fruits($arr, $i );
} else {
return $arr;
}
}
答案如下:
["apple","I like","apple","grape","watermelon","grape"]
希望这对您有所帮助!
答案 2 :(得分:0)
示例递归方法
$array = array("apple", "orange", "pear", "orange", "apple", "orange", "orange");
$key = "orange";
$value = "I like it";
// array_search will return index of the value if it exists in mentioned source
// empty actually check for a FALSE value.
while(!empty($index = array_search($key, $array))) {
$update = array($index => $value);
$array = array_replace($array, $update);
}
print_r($array); // all oranges are replaced with your