Home  >  Article  >  Backend Development  >  php实现搜索一维数组元素并删除二维数组对应元素的方法_PHP

php实现搜索一维数组元素并删除二维数组对应元素的方法_PHP

WBOY
WBOYOriginal
2016-05-30 08:45:31699browse

本文实例讲述了php实现搜索一维数组元素并删除二维数组对应元素的方法。分享给大家供大家参考。具体如下:

定义一个一维数组一个二维数组如下

$fruit=array('apple','orange');
$products = array( array('name'=>'apple','price'=>23.4),
array('name'=>'orange','price'=>45.3),
array('name'=>'biscuit','number'=>5,'price'=>34)
);

需要实现从$products数组中查找元素是否和数组$fruit元素有交集,如果有的话保留,否则删除.

实现方法为:

foreach($products as $key=>$value)
{
   if(!in_array($value["name"],$fruit))
   unset($products[$key]);
}
array_values($products);
//使用unset()销毁数组元素时候应注意索引问题最好使用array_values()给数组重新排序

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn