[英]get array value when comparing it
我有 2 個陣列fruit
Array(
[0]=>'Apple',
[1]=>'orange',
[2]=>'guava'
)
第二個數組是Allfruits
Array(
[0]=>'Strawberry',
[1]=>'Manggo',
[2]=>'durian',
[3]=>'Apple',
[4]=>'guava')
然后一個空數組調用$data
我的問題是如何在fruit
數組中不存在Allfruits
情況下插入它的成員?
所以在這個例子中,我希望結果是數據數組中除蘋果和番石榴之外的所有水果?
這是一個簡單的方法
$items_to_add = array_diff($array_fruit, $array_all_fruit);
$exclude_existing = array_diff($array_all_fruit, $array_fruit);
$new_array = array_merge($items_to_add, $exclude_existing);
通過使用以下函數,您可以合並 2 個數組而不會重復
function mergeArrayIfNotExist($childArray, $parentArray) {
for ($i = 0; $i < sizeof($childArray), $i++) {
if (!in_array($childArray[$i], $parentArray)) {
array_push($parentArray, $childArray[$i]);
}
}
return $parentArray;
}
只需運行一個循環並搜索$data數組中的值。 如果它在數組中,則使用array_search函數獲取它的索引並取消設置該值,否則將值添加到$data數組中。 如果需要,最后重新索引數組。
$check = ['Apple','orange','guava'];
$data = ['Strawberry','Manggo','durian','Apple','guava'];
foreach ($check as $key => $value) {
if(( $index = array_search( $value, $data )) !== false ){
unset( $data[$index] );
}else{
$data[] = $value;
}
}
$data = array_values( $data ); //for re-indexing the array
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.