你如何从foreach中删除一些数组

时间:2016-04-29 06:54:45

标签: php

我正在尝试从foreach中删除一些数组 “result”数组的示例:

    $result= array (  
  "1"  => array(
    "nickname" => "Jow",
    "Age"=> "19"
    ),
        "2"  => array(
    "nickname" => "Rayan",
    "Age"=> "25"
    ),
        "3"  => array(
    "nickname" => "Jinx",
    "Age"=> "21"
    ),
    );

我想通过昵称删除数组1 mycode:

foreach ($result as $client => $value){

if ( $value["nickname"] == "Jow"){

    unset($result[$client]);

    }
echo $value["nickname"].'<p>';

}

最终我想要剩下的名字如Rayan和Jinx

2 个答案:

答案 0 :(得分:1)

使用array_filter?

&#13;
&#13;
$result= array (  
  "1"  => array(
    "nickname" => "Jow",
    "Age"=> "19"
    ),
        "2"  => array(
    "nickname" => "Rayan",
    "Age"=> "25"
    ),
        "3"  => array(
    "nickname" => "Jinx",
    "Age"=> "21"
    ),
);

$arr = array_filter($result, 'filter_by_name');
var_dump($arr);exit;

function filter_by_name($value){
	if ($value['nickname']=='Jow') {
		return false;
	} else {
		return true;
	}
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你正在寻找这样的东西吗?

function removeByNickName($nickName, $array)
{
    $temp = array();
    foreach($array as $index => $ar)
    {
        if($array['nickname'] != $nickName) array_push($temp, $ar);
    }
    return $temp;
}