Jump to content

Array merge based on key

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
vale73

vale73

    Newbie

  • Members
  • Pip
  • 1 posts
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 ) )

#2
DEViANT

DEViANT

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 358 posts
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);

			}

		}

	}

?>


:D You should rep+ me so that I can win :D

My Blog | Ask me!
Error : Satan did it