Skip to content
Advertisement

Transform array, set each array element with parent key php

I am receiving data that is an array of elements that contains an array of tags by language like this

[
  {
    "1": "tag_es1;tag_es2;tag_es3",
    "2": "tag_en1;tag_en2;tag_en3"
  },
  {
    "1": "tag_es1;tag_es2",
    "2": "tag_en1;tag_en2"
  }
]

I need to separate each tag by language, so i usearray_map to transform it like this

[
  {
    "1": [
      "tag_es1",
      "tag_es2",
      "tag_es3"
    ],
    "2": [
      "tag_en1",
      "tag_en2",
      "tag_en3"
    ]
  },
  {
    "1": [
      "tag_es1",
      "tag_es2"
    ],
    "2": [
      "tag_en1",
      "tag_en2"
    ]
  }
]

Bu what i need is the response to be like this

[
  {
    {
      "1" : "tag_es1",
      "2" : "tag_en1"
    },
    {
      "1" : "tag_es2",
      "2" : "tag_en2"
    },
    {
      "1" : "tag_es3",
      "2" : "tag_en3"
    }
  },
  {
    {
      "1" : "tag_es4",
      "2" : "tag_en4"
    },
    {
      "1" : "tag_es5",
      "2" : "tag_en5"
    }

  }
]

I tried using array_combine, array_walk, and manually doing it inside array_map, but with no success, what could i do?

Advertisement

Answer

Solution with special trick with null as callback of array_map:

$arr = json_decode($s, true);
$new_arr = [];

foreach ($arr as $item) {
    $parts1 = explode(';', $item[1]);
    $parts2 = explode(';', $item[2]);

    // $new_arr[] = array_map(null, $parts1, $parts2);

    $tmp_arr = array_map(null, $parts1, $parts2);
    $new_arr[] = array_map(
        function($v) { return array_combine(["1","2"], $v); }, 
        $tmp_arr
    );
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement