...

View Full Version : Extracing keys and values from associative arrays



zingzangzung
08-21-2007, 10:41 AM
I have the following 2 dimensional array


$links = array(array('a1' => 'a1.php','a2' => 'a2.php','a3' => 'a3.php'),
array('b1' => 'b1.php','b2' => 'b2.php','b3' => 'b3.php'),
array('c1' => 'c1.php','c2' => 'c2.php','c3' => 'c3.php'),
array('d1' => 'd1.php','d2' => 'd2.php','d3' => 'd3.php')
);


I would like to extract the first keys and values form each sub array, to get the following. (don't know how many sub arrays, or their length in advance)


$firstLinks = array('a1' => 'a1.php','b1' => 'b1.php','c1' => 'c1.php','d1' => 'd1.php'),


I am struggling to find a simple solution. Can anyone assist?

matak
08-21-2007, 11:22 AM
I can't see a proper "simple" way, but this is how i played with it.. Almost made it, but..


<?php

$links = array(

array('a1' => 'a1.php','a2' => 'a2.php','a3' => 'a3.php'),
array('b1' => 'b1.php','b2' => 'b2.php','b3' => 'b3.php'),
array('c1' => 'c1.php','c2' => 'c2.php','c3' => 'c3.php'),
array('d1' => 'd1.php','d2' => 'd2.php','d3' => 'd3.php')
);


$firstLinks = array();

for ($i = 0; $i < count($links); $i++) {

$vals = (array_values($links[$i]));

$keys = (array_keys($links[$i]));

$Links = array ($vals[0] => $keys[0]);

array_push ($firstLinks, $Links);

}
print_r ($firstLinks);

?>

Inigoesdr
08-21-2007, 03:31 PM
$links = array(array('a1' => 'a1.php','a2' => 'a2.php','a3' => 'a3.php'),
array('b1' => 'b1.php','b2' => 'b2.php','b3' => 'b3.php'),
array('c1' => 'c1.php','c2' => 'c2.php','c3' => 'c3.php'),
array('d1' => 'd1.php','d2' => 'd2.php','d3' => 'd3.php')
);

$firstLinks = array();
foreach($links as $k)
{
$v = array_slice($k, 0, 1, 1);
$firstLinks[key($v)] = $v[key($v)];
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum