Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/forums/php/)
-   -   comparing two associative array (http://www.go4expert.com/forums/comparing-associative-array-t29836/)

c_user 27Sep2013 18:24

comparing two associative array
 
Hello friends,
Say i am having two array : ex1 and ex2 (both are associative array)
Can i compare array ex1 's value with array ex2 's key ?
Here is the example code i am trying to implement but ..
Code:

<?php

$marks=array('Odiy'=>'52' , 'Urdu'=>'69');



$postt=array ( 0=> array('id'=>'6', 'class_ref'=>'2nd' , 'subject_name'=>'Odiy') , 1=> array('id'=>'7', 'class_ref'=>'2nd' , 'subject_name'=>'Urdu') );

foreach($postt as $foo)
{
foreach($marks as $s)
{
if($foo['subject_name']==$s)
{
        echo "Hello";       
}
else
echo "NOT right";
}
}
var_dump($postt);
var_dump($marks);
?>

Show it in example ?
Thanks for the reply friends.
Take Care !

c_user 28Sep2013 11:42

Re: comparing two associative array
 
Lets me thanks http://php.net for giving me the base for R&D.
And the most importantly to @Shabbir sir ; for letting me know that above stated query is possible.

Coming to the solution part;
U cannot compare the Key of one array with the value of another array.
If u want to then u have to first make array whose values will the key of the array u are wanting to compare.
Then compare the two values of the array (one array's value are the key for another value ).

PHP Code:

<?php 

$marks
=array('Odiy'=>'52' 'Urdu'=>'69');

$postt=array ( 0=> array('id'=>'6''class_ref'=>'2nd' 'subject_name'=>'Odiy') , 1=> array('id'=>'7''class_ref'=>'2nd' 'subject_name'=>'Urdu') );

$keys=array_keys($marks);  // Here u are changing the keys to values of another array.

foreach($postt as $foo)
{
foreach(
$keys as $s)
{
if(
$foo['subject_name']==$s)
{
    echo 
"Hello"."<br>";    
}
else 
continue;
}
}

?>

The above prints:
Hello
Hello
.................................................. ................
This is what i got if u have any please share.
Thanking you.
Good day.

shabbir 28Sep2013 11:58

Re: comparing two associative array
 
Nicely done :D

c_user 30Sep2013 13:01

Re: comparing two associative array
 
Found another way of bypassing it.
PHP Code:

<?php 

$marks
=array('Odiy'=>'52' 'Urdu'=>'69');

$postt=array ( 0=> array('id'=>'6''class_ref'=>'2nd' 'subject_name'=>'Odiy') , 1=> array('id'=>'7''class_ref'=>'2nd' 'subject_name'=>'Urdu') );

$keys=array_keys($marks);

for(
$i=0;$i<count($postt);$i++)
{
for(
$j=0;$j<count($keys); $j++)
{
    if(
$j==$i)
    {
echo 
$postt[$i]['subject_name'];
echo 
$keys[$j];
    echo 
"<br>";    
}
else 
continue;
}
}


var_dump($marks);
var_dump($postt);
var_dump($keys);
?>

We can compare the index of the array using 'for' loop .
Did a small change that to make the the index of the marks turn to integer.
LoVe playing !
Take care !


All times are GMT +5.5. The time now is 06:00.