hi,
I've got two php arrays
The first array represents the total distance covered by a car, and I call it
$a
Array ( [0] => stdClass Object ( [total_distance] => 1000 [car_id] => 1 ) [1] => stdClass Object ( [total_distance] => 500 [car_id] => 2 ) )
The second array, is the array of cars, and I call it
$b
Array ( [0] => stdClass Object ([car_id] => 1 [year] => 2008 ) [1] => stdClass Object ( [car_id] => 2 [year] => 2010 ) )
Is it possible to merge these arrays, provided they have the car_id key in common?
The resulting array should be:
$c
Array ( [0] => stdClass Object ([car_id] => 1 [year] => 2008 [total_distance] => 1000 ) [1] => stdClass Object ( [car_id] => 2 [year] => 2010 [total_distance] => 500 ) )
Array merge based on key
Started by vale73, Dec 01 2010 07:55 AM
1 reply to this topic
#1
Posted 01 December 2010 - 07:55 AM
|
|
|
#2
Posted 01 December 2010 - 10:17 AM
I made you something :
<?php
class A
{
public $id;
public $distance;
function __construct($a,$b)
{
$this->id = $a;
$this->distance = $b;
}
}
class B
{
public $id;
public $year;
function __construct($a,$b)
{
$this->id = $a;
$this->year = $b;
}
}
$a = array(
'0' => new A('1','200'),
'1' => new A('2','400'));
$b = array(
'0' => new B('3','2010'),
'1' => new B('2','2009'));
$c = array();
foreach($a as $k1 => $v1)
{
foreach($b as $k2 => $v2)
{
if($v2->id == $v1->id)
{
$array = array(
'id' => $v1->id,
'distance' => $v1->distance,
'year' => $v2->year);
array_push($c,$array);
unset($array);
}
}
}
?>


Sign In
Create Account

Back to top









