Thursday, 30 August 2018

How to compare two arrays with condition using 'array_uintersec'?

I have the next arrays:

$noticias = [
    "0" => Array(
        "codigo" => "AMBITO"),
    "1" => Array(
        "codigo" => "ELSOL"),
    "2" => Array(
        "codigo" => "MDZ")
    ]

$portales = [
    "0" => Array(
        "codigo" => "LOSANDES"),
    "1" => Array(
        "codigo" => "MDZ"),
    "2" => Array(
        "codigo" => "ELSOL")
    ]

I need to compary both arrays by attribute codigo. The result would be:
$result = [
    "1" => Array(
        "codigo" => "ELSOL"),
    "2" => Array(
        "codigo" => "MDZ")
    ]

How can i do? At this moment, i have this:
$noticias_provinciales = array_uintersect($noticias, $portales, function($noticia, $portal_provincial){
                $portal_codigo_noticia = $noticia['Portal__codigo'];
                $portal_codigo_provincial = $portal_provincial->codigo;
                return ($portal_codigo_noticia === $portal_codigo_provincial ? 0: 1);
            });

But it doesn't work for me. I was debbuging and i notice that the both variables $noticia and $portal_provincial are from the same array ($noticia). I want that the first variable from function be $noticia (from $noticias) and the second one be $portal (from $portales). How can i do this?
Thanks!

I have put your code in a PHP sandbox and improved it, so the following will run at least under PHP 5.4.10 up to PHP 7.
$noticias = [
    "0" => Array(
        "codigo" => "AMBITO"),
    "1" => Array(
        "codigo" => "ELSOL"),
    "2" => Array(
        "codigo" => "MDZ")
]; // no changes here

$portales = [
    "0" => Array(
        "codigo" => "LOSANDES"),
    "1" => Array(
        "codigo" => "MDZ"),
    "2" => Array(
        "codigo" => "ELSOL")
]; // no changes here

$noticias_provinciales = array_uintersect($noticias, $portales, function($noticia, $portal_provincial){
            $portal_codigo_noticia = $noticia['codigo'];
            $portal_codigo_provincial = $portal_provincial['codigo'];
            return strcasecmp($portal_codigo_noticia, $portal_codigo_provincial);
        });

var_dump($noticias_provinciales);

The issues with your code were (from my point of view):
  • Access to the array members was wrong. $portal_provincial->codigo doesn't work as $portal_provincial is not an object. There is no index named 'Portal__codigo'.
  • The usage of strcasecmp($portal_codigo_noticia, $portal_codigo_provincial) and ($portal_codigo_noticia === $portal_codigo_provincial ? 0: 1) is not the same. Right now I can't explain why, but for me only strcasecmp() works. However, strcasecmp() is more elegant yet probably a bit slower.

0 comments:

Post a Comment