Your Location is: Home > Php

How do i merge meta keys? [closed]

From: Monaco View: 4671 Luke 

Question

I am using WordPress and ACF, I am wanting to merge the fields into one, please see below as an example

I have 3 fields that have outputs like this

a:3:{i:0;s:3:"157";i:1;s:3:"156";i:2;s:3:"155";}

I would like it to be in one array like this below

a:3:{s:4:"tags";a:4:{i:0;a:1:{i:0;s:2:"32";}i:1;a:1:{i:0;s:3:"100";}i:2;a:3:{i:0;s:3:"141";i:1;s:3:"138";i:2;s:3:"142";}i:3;a:1:{i:0;s:3:"137";}}s:7:"numbers";a:4:{i:0;s:1:"4";i:1;s:1:"2";i:2;s:1:"3";i:3;s:1:"1";}s:5:"marks";a:4:{i:0;s:1:"1";i:1;s:1:"1";i:2;s:1:"1";i:3;s:1:"1";}}

What is the best way of doing that upon submission of a form?

Thanks in advance

Best answer

Without knowing exactly how you want to merge them (unique/overwrite rules?), here's an idea of how to approach this. See comments for explanation. Outputs:

a:3:{s:4:"tags";a:5:{i:0;a:1:{i:0;s:2:"32";}i:1;a:1:{i:0;s:3:"100";}i:2;a:3:{i:0;s:3:"141";i:1;s:3:"138";i:2;s:3:"142";}i:3;a:1:{i:0;s:3:"137";}i:4;a:3:{i:0;s:3:"157";i:1;s:3:"156";i:2;s:3:"155";}}s:7:"numbers";a:4:{i:0;s:1:"4";i:1;s:1:"2";i:2;s:1:"3";i:3;s:1:"1";}s:5:"marks";a:4:{i:0;s:1:"1";i:1;s:1:"1";i:2;s:1:"1";i:3;s:1:"1";}}

Code:

<?php

$input = 'a:3:{i:0;s:3:"157";i:1;s:3:"156";i:2;s:3:"155";}';
/*
array(3) {
  [0]=>
  string(3) "157"
  [1]=>
  string(3) "156"
  [2]=>
  string(3) "155"
}
*/

// This is the original array before being serialized as the value you 
// show in your question.
$output = 
[
    'tags' =>
    [
        ['32'],
        ['100'],
        ['141', '138', '142'],
        ['137']
    ],
    'numbers' => [ '4', '2', '3', '1' ],
    'marks' => [ '1', '1', '1', '1' ]
];

// Add the new values as an array under 'tags'.
$output['tags'][] = unserialize($input);
echo serialize($output);
/*
Here's the native output array that we serialized:
array(3) {
  ["tags"]=>
  array(5) {
    [0]=>
    array(1) {
      [0]=>
      string(2) "32"
    }
    [1]=>
    array(1) {
      [0]=>
      string(3) "100"
    }
    [2]=>
    array(3) {
      [0]=>
      string(3) "141"
      [1]=>
      string(3) "138"
      [2]=>
      string(3) "142"
    }
    [3]=>
    array(1) {
      [0]=>
      string(3) "137"
    }
    [4]=>
    array(3) {
      [0]=>
      string(3) "157"
      [1]=>
      string(3) "156"
      [2]=>
      string(3) "155"
    }
  }
  ["numbers"]=>
  array(4) {
    [0]=>
    string(1) "4"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
    [3]=>
    string(1) "1"
  }
  ["marks"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "1"
    [2]=>
    string(1) "1"
    [3]=>
    string(1) "1"
  }
}
*/