我有以下任务要做,如果有任何机会我会感激一些帮助,以尽可能有效的方式。我需要比较来自对象数组(来自Laravel Query Builder连接查询)的值与数组值。
对象由数据库存储值组成:
0 => array:2 [
0 => {#912
+"addition_id": 1
+"valid_from": "2015-09-13 00:00:00"
+"valid_to": "2015-09-19 00:00:00"
+"price": "0.00"
+"mode": 0
+"alias": "Breakfast"
}
1 => {#911
+"addition_id": 2
+"valid_from": "2015-09-13 00:00:00"
+"valid_to": "2015-09-19 00:00:00"
+"price": "10.00"
+"mode": 1
+"alias": "Dinner"
}
while数组包含新数据,由我的方法处理。
0 => array:3 [
0 => array:6 [
"id" => 1
"alias" => "Breakfast"
"price" => "0.00"
"mode" => 0
"created_at" => "2015-09-12 21:25:03"
"updated_at" => "2015-09-12 21:25:03"
]
1 => array:6 [
"id" => 2
"alias" => "Dinner"
"price" => "10.00"
"mode" => 1
"created_at" => "2015-09-12 21:25:18"
"updated_at" => "2015-09-12 21:25:18"
]
2 => array:6 [
"id" => 3
"alias" => "Sauna Access"
"price" => "50.00"
"mode" => 0
"created_at" => "2015-09-12 21:25:35"
"updated_at" => "2015-09-12 21:25:35"
]
]
现在,我需要做的是找出数组中对象的位置(比较 id 与 addition_id )并返回它。
如果没有两个嵌套的foreach循环,有没有办法做到这一点?我认为可以通过array_filter以某种方式实现智能,但我并不确定如何编写高效的回调(这里是初学者)。
我唯一能解决这个问题的方法是:
private function compareAdditions(array $old,array $new)
{
$difference = $new;
foreach($new as $key => $value) {
foreach($old as $oldEntry) {
if($oldEntry->addition_id == $value['id']) {
unset($difference[$key]);
}
}
}
return $difference;
}
但我真的很想在没有两个foreach循环的情况下做到这一点。非常感谢帮助:)
答案 0 :(得分:1)
这可能有点矫枉过正,但它使用了我在每个项目中编写的函数,正是针对这些情况:
function additionals($original, $additions) {
$nonExisiting = [];
//convert all the objects in arrays
$additions = json_decode(json_encode($additions), true);
//create an index
$index = hashtable2list($original, 'id');
for(reset($additions); current($additions); next($additions)) {
$pos = array_search(current($additions)['addition_id'], $index);
if($pos !== false) {
//We could replace the originals with the additions in the same loop and save resources
//$original[$pos] = current($additions);
} else {
$nonExisiting[] = current($additions);
}
}
return $nonExisiting;
}
function hashtable2list( $hashtable, $key ){
$array = [];
foreach($hashtable as $entry) {
if( is_array($entry) && isset($entry[$key])) {
$array[] = $entry[$key];
} elseif( is_object($entry) && isset($entry->$key) ) {
$array[] = $entry->$key;
} else {
$array[] = null;
}
}
return $array;
}