我有这样的数组
Array ([0] =>
Array (
[user_id] => 21
[email] => momod@modara.com
[brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) )
[1] =>
Array (
[user_id] => 22
[email] => hemisphere@modara.com
[brand] => Array ( [0] => GOFUEL_W ) )
[2] =>
Array (
[user_id] => 23
[email] => madoka@modara.com
[brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
我想找到user_id 22并将此值“GO_FUEL_SGD_W”放在品牌上,我应该怎么做,所以数组的视图将如下所示
Array ([0] =>
Array (
[user_id] => 21
[email] => momod@modara.com
[brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) )
[1] =>
Array (
[user_id] => 22
[email] => hemisphere@modara.com
[brand] => Array ( [0] => GOFUEL_W => [1] =>GO_FUEL_SGD_W ) )
[2] =>
Array (
[user_id] => 23
[email] => madoka@modara.com
[brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
答案 0 :(得分:1)
一个简单的foreach循环将完成这项工作:
foreach($myarray AS &$subarray) {
if($subarray['user_id'] == 22) {
$subarray['brand'][] = "GO_FUEL_SGD_W";
break;
}
}
答案 1 :(得分:1)
只需使用循环:
foreach($array as &$item)
{
if(array_key_exists('user_id', $item) &&
$item['user_id']==22 &&
array_key_exists('brand', $item) &&
!in_array('GO_FUEL_SGD_W', $item['brand']))
{
$item['brand'][] = 'GO_FUEL_SGD_W';
}
}
答案 2 :(得分:1)
您需要迭代数组并查找您正在搜索的元素。
foreach ($array as &$element) {
if ($element['user_id'] != 22)
continue;
$element['brand'][] = "GO_FUEL_SGD_W";
break;
}
使用continue;
将跳过所有元素,其中$element['user_id'] != 22
(continue;
之后的所有代码都将被应用于它们!)。
由于break;
,一旦达到并修改了请求的元素,它也将结束循环。
答案 3 :(得分:0)
$array= //your array;
foreach($array as $x){
if($x['user_id']=='22'){
$x['brand'][]='GO_FUEL_SGD_W';
break;
}
}