[英]using foreach loop to delete last element from associative array
I want to delete price index from each of the array. 我想从每个数组中删除价格指数。
Here is a sample code: 这是一个示例代码:
Array([0] => Array
(
[player_id] => 108
[trnmnt_team_id] => 1
[player_type] => 1
[user_team_id] => 11
[user_id] => 4
[price] => 10.00
)
[1] => Array
(
[player_id] => 151
[trnmnt_team_id] => 2
[player_type] => 1
[user_team_id] => 11
[user_id] => 4
[price] => 10.00
)
)
I tried to delete following way but it shown unexpected 'unset' (T_UNSET)
: 我尝试按照以下方式删除,但显示意外的
'unset' (T_UNSET)
:
foreach ($mergeAllType as $key => $value) {
$price=$value;
$withOutPrice[]=unset($price['price']);
}
Tomas.lang's answer works fine if you know the last index's key. 如果您知道最后一个索引的键,那么Tomas.lang的答案就可以正常工作。 However if you don't know the name of the last key you could use the following:
但是,如果您不知道最后一个键的名称,则可以使用以下命令:
unset(end($price));
$withOutPrice = $price;
You already got your answers regarding your foreach loop. 您已经获得了有关foreach循环的答案。
So, let me give you a different answer, using array_map and an anonymous function ;-) 所以,让我给您一个不同的答案,使用array_map和一个匿名函数 ;-)
<?php
$src = array(
array (
'player_id' => 108,
'trnmnt_team_id' => 1,
'player_type' => 1,
'user_team_id' => 11,
'user_id' => 4,
'price' => 10.00,
),
array (
'player_id' => 151,
'trnmnt_team_id' => 2,
'player_type' => 1,
'user_team_id' => 11,
'user_id' => 4,
'price' => 10.00,
),
);
$withOutPrice = array_map(
function($e) {
unset($e['price']);
return $e;
},
$src
);
var_export($withOutPrice);
If you want to unset()
all off the price
keys in your array you can use array_walk()
如果要
unset()
数组中所有price
键,可以使用array_walk()
array_walk($arr, function(&$array) {
unset($array['price']);
});
Just replace $arr
with whatever your arrays name is, ie $teams
. 只需将
$arr
替换$arr
您的数组名称即$teams
。
If you want to have two arrays, one with price and one without price you could duplicate the array before doing the above; 如果要有两个数组,一个带有价格,另一个不带价格,则可以在执行上述操作之前复制该数组; ie
即
$teams = <DATASOURCE>
$teamsWithoutPrice = $teams;
array_walk($teamsWithoutPrice, function(&$array) {
unset($array['price']);
});
Then if you print out your $teamsWithoutPrice
array you'll have your array with the price
key removed. 然后,如果您打印出
$teamsWithoutPrice
数组,则将删除price
键。
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.