简体   繁体   English

更改php数组值

[英]changing php array value

I have this very very basic code 我有这个非常非常基本的代码

  foreach ($formatted_results as $result) {
          $result['profile_pic']="joe";//set all values to joe
              var_dump( $result['profile_pic']);//prints joe
        }
  foreach ($formatted_results as $result) {

              var_dump( $result['profile_pic']);//does not print joe!
        }

where formatted_results is an array containing other arrays. 其中formatted_results是包含其他数组的数组。 Now as you can see, I am modifying in the first loop the value of every array within formatted_results to contain the name joe, and then I am printing that to make sure and sure enough, the print of the first loop returns "joe" 现在,您可以看到,我在第一个循环中修改了formatted_results中每个数组的值,以包含名称joe,然后我进行打印以确保确定,第一个循环的打印返回“ joe”

However, the value I set is not persisting somehow, as when I loop that same array again to check the inner values of its own arrays, it gives me the old value. 但是,我设置的值不会以某种方式持久化,因为当我再次循环同一数组以检查其自身数组的内部值时,它为我提供了旧值。

The code is exactly as I am displaying it here, there is nothing in between. 该代码与我在此处显示的代码完全一样,两者之间没有任何关系。 I am guessing there is something about pointers that is eluding me here. 我猜想这里有一些关于指针的东西使我难以理解。

The value is not set to the actual array , rather assigned to the current element which is not available outside the loop. 该值未设置为实际array ,而是分配给了在循环外不可用的当前元素。 You need to set the value to the actual array you are looping through. 您需要将值设置为要遍历的实际array Try - 尝试-

foreach ($formatted_results as &$result) {
    $result['profile_pic']="joe";//set all values to joe
}

foreach - Pass by reference foreach-通过引用传递

Here is the code : 这是代码:

    foreach ($formatted_results as $k =>  $result) {
          $formatted_results[$k]['profile_pic']="joe";//set all values to joe
              var_dump( $formatted_results[$k]['profile_pic']);//prints joe
        }
  foreach ($formatted_results as $result) {

              var_dump( $result['profile_pic']);//does not print joe!
        }

$result is not gonna save data to $formatted_results $ result不会将数据保存到$ formatted_results

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM