Edgar
Edgar

Reputation: 1131

Combining 2 arrays into one

I got 2 arrays:

  $ping_array = array();
  $ping_array[] = '400';
  $ping_array[] = '200';
  $ping_array[] = '600';
  $ping_array[] = '100';

  $timestamp_array = array();
  $timestamp_array[] = '2013-03-25 16:30:07';
  $timestamp_array[] = '2013-03-25 16:30:39';
  $timestamp_array[] = '2013-03-25 18:30:06';
  $timestamp_array[] = '2013-03-25 18:45:49';

I want to make something like this (i dont know how its called):

 $combined_array = array( 
                    'time' => $timestamp_array,
                    'ping' => $ping_array

                   );

so later on i could use the 2 arrays combined like this:

foreach ($combined_array as $ca=> $values) {
echo $values['ping'];
echo $values['time'];

}

Thx guys this combine_array is amazing

Upvotes: 0

Views: 88

Answers (5)

Dave
Dave

Reputation: 29141

PHPs array_combine: "Creates an array by using one array for keys and another for its values"

$combined_array = array_combine($timestamp_array, $ping_array);

Then just repeat through similar to what you included:

foreach($combined_array as $time => $ping) {
    echo $ping;
    echo $time;
}

Upvotes: 1

Martinsos
Martinsos

Reputation: 1693

What you could do is make array of objects, like this:

class PingInfo {
    public $ping;
    public $time;
    public function PingInfo($ping, $time) {
        $this->ping = $ping;
        $this->time = $time;
    }
}

$pingInfos = array();
$pingInfos[] = new PingInfo('400', '2013-03-25 16:30:07');
$pingInfos[] = new PingInfo('300', '2013-03-25 16:50:13');

You could build it from two array like this:

$pingInfos = array();
for ($i = 0; $i < count($ping_array); $i++)
    $pingInfos[] = new PingInfo($ping_array[$i], $timestamp_array[$i]);

Now you can access it like this:

foreach ($pingInfos as $pingInfo) {
    echo $pingInfo->ping;
    echo $pingInfo->time;
}

Upvotes: 0

Ares
Ares

Reputation: 5903

How about php 'array_merge_recursive'? It does exactly what you are looking for. It is found on php 4 and up.

Upvotes: 0

mkjasinski
mkjasinski

Reputation: 3088

Try this:

$combined_array = array();
foreach ($ping_array as $key => $value){
    $combined_array[] = array(
        'time' => $timestamp_array[$key],
        'ping' => $value
    );
}

Upvotes: 4

fedorqui
fedorqui

Reputation: 290525

What about this?

for ($i=0; $i<count($timestamp_array); $i++) {
     $combined_array[$i]["ping"] = $ping_array[$i];
     $combined_array[$i]["time"] = $timestamp_array[$i];
}

Upvotes: 2

Related Questions