简体   繁体   中英

trouble with array_merge, serialize and unserialize in php

I have to do this:

  1. take an associative array and insert it into a field in my database so I can re-use it as associative array. [DONE with serialize($associativeArray)]
  2. take the associative array from the database and view as array. [DONE with unserialize($arraySerializedBefore) ]
  3. Merge an array already in the database (serialized) with an array just created.

For example:

Array 
( 
  [1] => 'nanananana,lol,',
  [2] => 'laaaaalalalala,asd,',
  [3] => 'r0tfl,lmfao,ahah,'
)

Second array to merge with the first:

Array 
( 
  [1] => 'dunnoWhat,write,',
  [3] => 'hello,wooorld,'
)

So I need a final array like this:

Array 
( 
  [1] => 'nanananana,lol,\N,dunnoWhat,write,',
  [2] => 'laaaaalalalala,asd,',
  [3] => 'r0tfl,lmfao,ahah,\N,hello,wooorld,'
)

If you see it merge it using the key, if they have the same key, it adds a "\\n" to go in a new line (the same of BR tag...it's only an example) and after it add the string of the second array correspondent to the key. However if you don't understand watch the example and you will. Thanks

Traverse the second array using a foreach and match its keys with the one with the first array and if match found, Update the first array by concatenation.

<?php

$arr1=Array(1 => 'nanananana,lol,',2 => 'laaaaalalalala,asd,',3 => 'r0tfl,lmfao,ahah,');
$arr2=Array(1 => 'dunnoWhat,write,',3 => 'hello,wooorld,');

$i=min(array_keys($arr1));
foreach($arr2 as $k=>$val)
{
    if(array_key_exists($k,$arr1))
    {
    $arr1[$k].='\N, '.$val;
    }

}
print_r($arr1);

OUTPUT :

Array
(
    [1] => nanananana,lol,\N, dunnoWhat,write,
    [2] => laaaaalalalala,asd,
    [3] => r0tfl,lmfao,ahah,\N, hello,wooorld,
)

I just was wondering if it's possible to resolve with one functional block (like functional programming). It is:

$foo = [
   0 => "test zero",
   1 => "test one",
   2 => "test two",
   3 => "test three"
];

$bar = [
   1 => "test four",
   5 => "test five",
   3 => "test six",
   4 => "test seven"
];

$result = 
   array_diff_key($foo, $bar)
   +
   array_combine(
      $y = array_keys(array_intersect_key($foo, $bar)), 
      array_map(function($x) use ($foo, $bar)
      {
         return $foo[$x]."\n".$bar[$x];
      }, $y)
   )
   +
   array_diff_key($bar, $foo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM