0

I have an array and I don’t know how to change it to the structure I need: My array:

array (
  "1536" => "12",
  "1695" => "Korea",
  "1904" => "10/7",
  "1905" => "",
  "1906" => null,
  "1907" => "1.1",
  "1906.1" => "H1",
  "1906.2" => "H35",
  "1905.1" => "15"
)

I need to cast this array to this form (remove the tenths of the numbers, and paste the values of the same numbers into the array):

array (
  "1536" => "12",
  "1695" => "Korea",
  "1904" => "10/7",
  "1905" => array("", "15"),
  "1906" => array(null, "H1", "H35"),
  "1907" => "1.1"
)
2
  • 3
    Jay Blanchard, this is not a duplicate of the question you linked to. Commented Sep 6, 2019 at 11:59
  • What have you tried so far? Maybe a foreach with index parsing... Commented Sep 6, 2019 at 14:54

1 Answer 1

1

Make an iteration over the array using array_walk(). In every cycle of the iteration check weather the key already exist in the $res array. If exist then create array merging with old value and assign to the same key. If not key already exist then assign the $val to the $res array.

$data = array("1536" => "12","1695" => "Korea","1904" => "10/7","1905" => "", "1906" => null,"1907" => "1.1","1906.1" => "H1","1906.2" => "H35","1905.1" => "15");

$res = array();
array_walk($data, function($val, $key) use(&$res) {
    $key = intval($key);
    if (array_key_exists($key, $res)) {
        $res[$key] = is_array($res[$key]) ? array_merge($res[$key], [$val]) : array_merge([$res[$key]], [$val]);
    } else {
        $res[$key] = $val;
    }
});

print_r($res);

Working demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.