从数组php中删除特定的key =>值

时间:2014-02-20 10:30:57

标签: php arrays unset

我有一个像这样的数组

Array
(
    [0] => Array
        (
            [to_id] => 3
            [email] => ngkarthick.kumar@gmail.com
            [user_id] => 3
        )

    [2] => Array
        (
            [to_id] => 2
            [email] => karthickkumarganesh@gmail.com
            [user_id] => 2
        )

    [4] => Array
        (
            [to_id] => 5
            [email] => phpkarthick@outlook.com
            [user_id] => 5
        )

)

我希望得到如下数组

Array
(
    [0] => Array
        (
            [email] => ngkarthick.kumar@gmail.com
            [user_id] => 3
        )

    [2] => Array
        (
            [email] => karthickkumarganesh@gmail.com
            [user_id] => 2
        )

    [4] => Array
        (
            [email] => phpkarthick@outlook.com
            [user_id] => 5
        )

)

我通过使用foreach循环来完成这项工作,但我想做单阵列功能,是否有可能,请帮助

2 个答案:

答案 0 :(得分:4)

$array = array_map(
    function (array $ar) { return array_diff_key($ar, array_flip(array('to_id'))); },
    $array
);

没有一个单一的功能可以做到这一点。你必须写一些代码。您还必须循环遍历数组。你只能以不同的方式打扮这个循环,并以不同的方式打扮不放松钥匙的动作。我不一定认为任何东西比直接循环更有效或更清晰。但是,如果你正在寻找更加花哨的东西,那就去吧。

答案 1 :(得分:0)

//This is the array name in which your data is stored.
$my_array = array($array_data);

// now lets get one level inside the array 
foreach($my_array as $key => $value ){

// ok now unset un-wanted index from the array into a temporary array
unset($value['to_id']);

// overwrite our temporary array to original array keeping the keys same as before.
$my_array[$key] = $value;
//Thats it your Problem Solved :)
}

echo "<pre>";
print_r($my_array);
echo "</pre>";
相关问题