Jump to content

Combining Two Unequal Arrays by Matching Keys


claro

Recommended Posts

I have here two arrays. Array1 has a related value to array2. What I need is that I'm going to save both values at once. I've used 'array_combine' function but my arrays are having unequal keys. Any help is greatly appreciated. Thank you.

 

$type = $_POST['dev_type'];
$sn = $_POST['dev_sn'];
Array
(
   [0] => 22
   [1] => 19
   [2] => 66
   [3] => 62
   [4] => 64
)
Array
(
   [0] => sn1
   [1] => sn2
   [2] => sn3
)

This is most likely a problem with the PHP code that generates the HTML, which generates the values above. You need to establish the relationship between the values at the earliest possible moment, preferably via the keys (if they hold no other significant information).

Doing that should make it trivial to match them up after the form has been submitted.

do you mean something like this?

 

<?php

$type = Array
(
    0 => 22,
    1 => 19,
    2 => 66,
    3 => 62,
    4 => 64
);

$sn = Array
(
    0 => sn1,
    1 => sn2,
    2 => sn3,
    5 => sn4
);

$result = array();
foreach ($type as $k => $v1) {
   $v2 = '';
   if (isset($sn[$k])) {
    $v2 = $sn[$k];
    unset ($sn[$k]);
   }
   $result[$k] = array ('type'=>$v1, 'sn'=>$v2);
}

// now any remaining in sn array
foreach ($sn as $k=>$v2) {
   $result[$k] = array ('type'=>0, 'sn'=>$v2);
}

echo '<pre>',print_r($result, true),'</pre>';


/*
RESULTS:

Array
(
   [0] => Array
    (
	    [type] => 22
	    [sn] => sn1
    )

   [1] => Array
    (
	    [type] => 19
	    [sn] => sn2
    )

   [2] => Array
    (
	    [type] => 66
	    [sn] => sn3
    )

   [3] => Array
    (
	    [type] => 62
	    [sn] =>
    )

   [4] => Array
    (
	    [type] => 64
	    [sn] =>
    )

   [5] => Array
    (
	    [type] => 0
	    [sn] => sn4
    )

)
*/
?>

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.