Reputation: 131
I have two arrays. One contains json-formatted objects with 2 variables each, so like array(3){["John"]=>string(2)"20" ["Mary"]=>string(2)"18" ["Paul"]=>string(2)"23"}. This shows people's names and their age. These ages are to be entered in the form on the browser and sent to the server using GET request. The other array contains objects of those people where the names are in common, but not their age. Each object has been created from a class and contains their name and their job. This array was created like this:
<?php
class Person{
private $name;
private $job;
}
/*constructor*/
public function __construct($name, $job){
$this->name = $name;
$this->job = $job;
}
/*getters*/
public function getName(){
return $this->name;
}
public function getOccupation(){
return $this->job;
}
$john = new Person("John", "Police Officer");
$mary = new Person("Mary", "Actress");
$paul = new Person("Paul", "Professor");
/* ... and more people */
/*the second array contains all these data*/
$people = array($john, $mary, $paul, /* more people */);
?>
As you can see, these arrays have name variable in common. What I want to do is, inside foreach which goes through the first array, check if the same name appears in the second array, and if it does, retrieve that person's job title. Assume that both of these arrays are a lot bigger than this and the order of data is different. I am not sure how to approach this. First I tried to check if the comparison itself works, but it does not work and I cannot figure it out why.
<?php
foreach($_GET as $name => $age){
echo $name;
foreach($people as $person){
if($person->getName() == $name){
echo $person->getOccupation();
}
}
}
?>
This prints nothing. Can anyone help me what is going on? Thank you in advance!
EDIT: I am actually trying to achieve this inside HTML tag.
<table>
<tr>
<th>Name</th>
<th>Occupation</th>
</tr>
<?php foreach($_GET as $name => $quantity): ?>
<tr>
<td><?php echo $name ?></td>
<?php foreach($people as $person): ?>
<?php if($person->getName() == $name): ?>
<td><?php echo $person->getOccupation(); ?></td>
<?php endif ?>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
Upvotes: 0
Views: 2080
Reputation: 7004
Try like this...
<?php
$person=array(array('name'=>'aa','occupation'=>'xx'),array('name'=>'bb','occupation'=>'yy'),array('name'=>'cc','occupation'=>'zz')); //this is your array people
//print_r($person);
$name ='cc';//assume
foreach($person as $k=>$v)
{
if($v['name'] == $name)
{
echo $v['occupation'];//outputs zz which is occupation of cc matched with $name
}
}
?>
Not need to make function call..because values are already in array..so like this...
<?php
foreach($_GET as $name => $age){
echo $name;
foreach($people as $person=>$value){
if($value['name'] == $name)
{
echo $value['occupation'];
}
}
}
?>
Upvotes: 1