php list 更改,無法更改php列表中的值 - Can't change a value inside a php list - 开发者知识库...

该博客探讨了如何在PHP循环中将数组转换为列表并修改元素值,分享了三种方法:使用foreach循环带引用、直接修改数组元素和利用each()函数的特点。作者解释了每种方法的工作原理,并指出更推荐的高效方式。
摘要由CSDN通过智能技术生成

I have the following php loop that takes an array that contains a set of arrays. I use this code to convert each array to a list, so I can manipulate the elements better.

我有以下php循環,它接受一個包含一組數組的數組。我使用此代碼將每個數組轉換為列表,因此我可以更好地操作元素。

This is my code...

這是我的代碼......

while ($i

while(list($key,$val) = each($my_array[$i])){

$j = $i+1;

if ($key == "fruit"){

$val = "ananas".$j;

echo $val;

}

}

$i++;

}

When I print the "search" array (print_r($my_array)), the values don't change. I don't understand why this doesn't work as I had expected. Is there a solution to modify the $val without changing the loop structure and logic?

當我打印“搜索”數組(print_r($ my_array))時,值不會更改。我不明白為什么這不像我預期的那樣有效。有沒有一個解決方案來修改$ val而不改變循環結構和邏輯?

3 个解决方案

#1

3

Use foreach with reference:

使用foreach參考:

$i = 0;

foreach ( $my_array as $key => &$val ) {

++$i;

if ($key == "fruit"){

$val = "ananas" . $i;

echo $val;

}

}

#2

1

$val is a copy of the data contained in $my_array[$i], not the actual data. To change the data in the array:

$ val是$ my_array [$ i]中包含的數據的副本,而不是實際數據。要更改數組中的數據:

while ($i

while(list($key,$val) = each($my_array[$i])){

$j = $i+1;

if ($key == "fruit"){

$my_array[$i][$key] = "ananas";

echo $my_array[$i][$key];

}

}

$i++;

}

And it's probably easier to use a foreach loop

並且使用foreach循環可能更容易

#3

0

each() doesn't pass the data as references, without modifying the loop that much:

each()不會將數據作為引用傳遞,而不會修改循環:

if ($key == "fruit"){

$val = "ananas";

echo $val;

$my_array[$i][$key] = $val;

}

Of course, there are better ways to do that. But you wanted an answer that didn't change the loop structure.

當然,有更好的方法可以做到這一點。但是你想要一個沒有改變循環結構的答案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值