Văn Lộc Văn Lộc - 1 month ago 12
PHP Question

Compare two columns of an array in PHP?

I have an array

$get_list_cate
.

So, I want to compare values of two columns in this array.

Array
$get_list_cate
:

ID..................PARENT_ID.....................NAME
0 5 Ashe
1 3 Garen
2 0 Yasuo
4 1 Miss Fortune
5 2 Veikor


So, I tried to loop through this array and tried to compare all values of
id
with all values of
parent_id
. Here my code:

<?php foreach($get_list_cate as $item_cate):

if($item_cate->parent_id == $item_cate->id ) :
// some code
endif

endforeach
?>


But it will like this:

Only 5 is values of `parent_id` : - compare to - : all values in `id`.


5 ---- 0
---- 1
---- 2
---- 4
---- 5 -> correct.


Stop at here. Is not two
foreach
.

It should continue with:

3 ----- 0
---- 1
---- 2
---- 4
---- 5


=> not available in this array.

0 ----- 0 -> correct.
---- 1
---- 2
---- 4
---- 5


More and more....

Answer

Explanations:

  1. The usage of this operator called -> which is used for getting of the objects from the array.
  2. But when you are going to loop through the array values which comes from the DB you have to use the operator called $data['DB COLUMN NAME'] to fetch the data or do what ever as you wish.
  3. Where $data is the variable that comes in the loop.

Hence this might be code code you need to use.

If you need to compare with one foreach() for the single array you get.

<?php 
foreach($get_list_cate as $single_item)
{
   if($single_item['id'] == $single_item['parent_id'])
    {
        // You can handle upon the condition if TRUE
    }
    else
    {
        // You can handle the FALSE Request over here
    }
}
?>

If you need to compare with Two foreach() for the array you get.

(E.g) You need to compare the ID from the first array and the PARENT_ID from the second array you can use the below code.

<?php 
foreach($get_list_cate as $key1=>$single_item)
{
    foreach ($single_item as $key2 => $single_value) 
    {
            if($key2==$key1)    
            {
                if($single_value['parent_id'] == $single_item['id'])
                {
                    // You can handle upon the condition if TRUE
                }
                else
                {
                // You can handle the FALSE Request over here
                }           
            }
    }
}
?>

Alternative Solution:

If you have two arrays namely $array1 and $array2 you can perform the array_diff() in order to fetch out the odd one alone. It pulls out the differed value from the array if you use the array_diff() function.

Code:

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>

Output:

Array
(
    [1] => blue
)
Comments