Reputation: 7520
Just need a little help here about arrays. Because I am trying to create a code that when you click it it will replace a certain array values.
In the base array suppose that we have this array:
Array(
[0] => Array(
[id] => 1,
[name] => xyz
),
[1] => Array(
[id] => 4,
[name] => fsa
),
)
And in my new array I have something like this
Array(
[id] => 4,
[name] => pop
)
I have a validation like this: In the base array I put this array in $base_array and in my new array I have $update_array
$get_updated_array_id = $update_array[id];
for($x = 0; $x <= sizeof($base_array); $x++){
$target = $base_array[$x]['id'];
if($get_updated_array_id == $target){
//should be replace the array value ID '4'
}
}
So the final result should be:
Array(
[0] => Array(
[id] => 1,
[name] => xyz
),
[1] => Array(
[id] => 4,
[name] => pop
),
)
Any idea how can I do that? Thanks
Upvotes: 0
Views: 62
Reputation: 1153
//PHP >= 5.3
array_walk($base_array, function (& $target) use ($update_array) {
if ($target['id'] == $update_array['id']) {
$target = $update_array;
}
});
Upvotes: 1
Reputation: 297
$new_array = array(
[id] => 4,
[name] => pop
);
$get_updated_array_id = $update_array[id];
for($x = 0; $x <= sizeof($base_array); $x++){
$target = $base_array[$x]['id'];
if($get_updated_array_id == $target){
$base_array[$x] = $new_array;
}
}
Upvotes: 1
Reputation: 3256
<?php
$array = array(
array('id' => 2,'name' => 'T'),
array('id' => 4,'name' => 'S')
);
$replace = array('id' => 4,'name' => 'New name');
foreach ($array as $key => &$value) {
if($value['id'] == $replace['id'] ) {
$value = $replace;
}
}
print_r($array);
Upvotes: 2