Jump to content

combining multi-dimensional arrays


rubing

Recommended Posts

Hey all,

 

I am trying to figure out how to perform combine operations on multi-dimensional arrays, but can't figure out how to iterate over the subarrays and then combine them.

 

 

$arrayA has 28 elements

 

$arrayB also has 28 elements, but every element is a sub-array with n-values

 

$arrayC is similar to $arrayB, also having 28 elements where every element is a subarray.  The subarrays have the same n-number of values as arrayB, but with different values.

Link to comment
https://forums.phpfreaks.com/topic/104019-combining-multi-dimensional-arrays/
Share on other sites

But I want to combine the two arrays not append one on to the other.  For example if my first 2-dimensional array is:

 

Array ( [Array] => Array ( [0] => Array ( [0] => blue  [1] => red  [2] => white ) [1] => Array ( [0] => navy  [1] => grey  ) ) )

 

And my second 2-dimensional array is:

 

Array ( [Array] => Array ( [0] => Array ( [0] => ferari  [1] => dodge  [2] => cadilac  ) [1] => Array ( [0] => jeans  [1] => loafers  ) ) )

 

How would I combine these so that one has the values and the other has the key like array_combine would? 

try

<?php
$a = Array('Array' => Array(Array('blue',   'red',   'white'  ), Array ('navy', 'grey')),2);
$b = Array('Array' => Array(Array('ferari', 'dodge', 'cadilac'), Array('jeans', 'loafers')),9);
function my_combine($keys, $values) {
$out = array();
if (count($keys) != count($values)) return false;
$a = array_keys($keys);
$b = array_keys($values);
for ($i = 0; $i < count($keys); $i++){
	if (is_array($keys[$a[$i]])){
		if (is_array($values[$b[$i]])){
			$out[$a[$i]] = my_combine($keys[$a[$i]], $values[$b[$i]]);
		} else return false;
	} else if (is_array($values[$b[$i]])) return false;
	$out[$keys[$a[$i]]] = $values[$b[$i]];
}
return $out;
}
$c=my_combine($a,$b);
print_r($c);
?>

try

<?php
$a = Array('Array' => Array(Array('blue',   'red',   'white'  ), Array ('navy', 'grey')),2);
$b = Array('Array' => Array(Array('ferari', 'dodge', 'cadilac'), Array('jeans', 'loafers')),9);
function my_combine($keys, $values) {
$out = array();
if (count($keys) != count($values)) return false;
$a = array_keys($keys);
$b = array_keys($values);
for ($i = 0; $i < count($keys); $i++){
	if (is_array($keys[$a[$i]])){
		if (is_array($values[$b[$i]])){
			$out[$a[$i]] = my_combine($keys[$a[$i]], $values[$b[$i]]);
                                if ($out[$a[$i]]===false) return false;
		} else return false;
	} else if (is_array($values[$b[$i]])) return false;
	else $out[$keys[$a[$i]]] = $values[$b[$i]];
}
return $out;
}
$c=my_combine($a,$b);
print_r($c);
?>

i miss one else

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.