arrays - PHP array_udiff functionality -
i'm trying find elements of 1 array not in array in php. under impression should using array_udiff
function custom defined callback.
the first array array of objects id property. second array array of objects name property. name properties contain id number within string makes name.
my goal make sure each object's id in first array has corresponding object in second array contains it's id within name. here's code:
<?php class nameobj { public $name; function __construct($name){ $this->name = $name; } } class idobj{ public $id; function __construct($id){ $this->id = $id; } } $idarray = array( new idobj(1), new idobj(2), new idobj(3) ); $namearray = array( new nameobj('1 - object 1 name'), new nameobj('2 - object 2 name') ); function custom_diff($oid, $oname){ $splitname = explode(' - ', $oname->name); $idfromname = $splitname[0]; $id = $oid->id; if($idfromname == $id) return 0; return $idfromname > $id ? 1 : -1; } $missing_objects = array_udiff($idarray, $namearray, 'custom_diff'); print_r($missing_objects); ?>
i expect see array containing third object first array, instead this:
php notice: undefined property: idobj::$name in /home/ubuntu/test2.php on line 33 php notice: undefined property: idobj::$name in /home/ubuntu/test2.php on line 33 php notice: undefined property: nameobj::$id in /home/ubuntu/test2.php on line 36 php notice: undefined property: idobj::$name in /home/ubuntu/test2.php on line 33 php notice: undefined property: idobj::$name in /home/ubuntu/test2.php on line 33 array ( [1] => idobj object ( [id] => 2 ) [2] => idobj object ( [id] => 3 ) )
what missing here? using array_udiff
function incorrectly?
you using incorrectly. specifically, assuming called item first array , item second array, in order, arguments. php not make such guarantee.
now make comparison detect types of arguments , act accordingly, that's not best idea because it's swimming against current. array_udiff
supposed operate on structured arrays, these not. additionally, don't need check each element of first array against each element of second achieve goal.
here's how (borrowing bit of code):
$extractor = function($o) { return explode(' - ', $o->name)[0]; }; $idsfromnames = array_flip(array_map($extractor, $namearray)); foreach ($idarray $k => $o) { if (!isset($idsfromnames[$o->id])) { unset($idarray[$k]); } }
Comments
Post a Comment