i have a 2d array
$arr = array (
array('x'=>'x1' , 'y'=>'') ,
array('x'=>'x2' , 'y'=>'')
);
as you can see the y column is empty
if i want to put some value on it this doesn't works
foreach($arr as $a )
{
if($a['x'] == 'x1')
$a['y'] = 'y1';
if($a['x'] == 'x2')
$a['y'] = 'y2';
}
i know i can use 2 for
loops , but i was wondering if there is a cleaner/simpler way like foreach to do this ? my application already uses the froeach loop to check some column in array and it's messy enough already i don't need 2 other loops !
The problem is you are using the array values instead of the keys. The following code will do it:
<?php
$arr = array (
array('x'=>'x1' , 'y'=>'') ,
array('x'=>'x2' , 'y'=>'')
);
foreach($arr as $key => $value )
{
if($arr[$key]['x'] == 'x1')
$arr[$key]['y'] = 'y1';
if($arr[$key]['x'] == 'x2')
$arr[$key]['y'] = 'y2';
}
?>
As you can see, you should use the $key => $value notation for foreach.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.