如何从另一个数组中删除一个数组元素? [英] How do I remove an array elements from another array?

查看:183
本文介绍了如何从另一个数组中删除一个数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组。如何删除另一个数组(即 $ remove )中存在的所有那些元素,并重新索引从1开始而不是从0开始的最终数组?

I have this array. How do I remove all those elements which are present in another array i.e. $remove and re-index the final array starting from 1 not 0?

  $info =  array(
    '1' => array('name' => 'abc', 'marks' => '56'),
    '2' => array('name' => 'def', 'marks' => '85'),
    '3' => array('name' => 'ghi', 'marks' => '99'),
    '4' => array('name' => 'jkl', 'marks' => '73'),
    '5' => array('name' => 'mno', 'marks' => '59')
  );
  $remove = array(1,3);

所需输出:

  $info =  array(
    '1' => array('name' => 'def', 'marks' => '85'),
    '2' => array('name' => 'jkl', 'marks' => '73'),
    '3' => array('name' => 'mno', 'marks' => '59')
  );

到目前为止,我已经尝试了这两种方法。没什么对我有用。

So far I've tried these two methods. Nothing worked for me.

  if (($key = array_search(remove[0], $info))) {
    unset($info[$key]);
    $info = array_values($info);
  }

  $result = array_diff($info, $remove);


推荐答案

类似的方法将起作用:

$result = array_diff_key( $info, array_flip( $remove));

array_flip() 是您的 $ remove 数组,因此键变为值,而值变为键。然后,我们使用 array_diff_key() 两个数组的以获得此结果

This array_flip()s your $remove array so the keys become the values and the values becomes the keys. Then, we do a difference against the keys with array_diff_key() of both arrays, to get this result:

Array
(
    [2] => Array
        (
            [name] => def
            [marks] => 85
        )

    [4] => Array
        (
            [name] => jkl
            [marks] => 73
        )

    [5] => Array
        (
            [name] => mno
            [marks] => 59
        )

)

最后,要产生准确的输出,您可以通过 array_values() 将数组重新索引,但这会产生从零开始的顺序索引,而不是一个:

Finally, to yield your exact output, you can reindex your array by passing it through array_values(), but this will yield sequential indexes starting at zero, not one:

$result = array_values( array_diff_key( $info, array_flip( $remove)));

如果您确实需要从一个索引开始,那么您将需要一个 array_combine() range()

If you really need indexes to start at one, you will need a combination of array_combine() and range():

$result = array_diff_key( $info, array_flip( $remove));
$result = array_combine( range( 1, count( $result)), $result);

这篇关于如何从另一个数组中删除一个数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆