1

There is the following array in my application:

array (
    [item_name_1] => GTA V
    [item_quantity_1] => 4
    [item_price_1] => 5990
    [item_name_2] => Watch_Dogs
    [item_quantity_2] => 1
    [item_price_2] => 5990
)

I want to divide/split this array into two pieces like that:

array (
    [item_name_1] => GTA V
    [item_quantity_1] => 4
    [item_price_1] => 5990
)

array (
    [item_name_2] => Watch_Dogs
    [item_quantity_2] => 1
    [item_price_2] => 5990
)

If you didn't realized, I want to separate items suffixed by 1 and 2 – and successively – unto different matrices and I really don't see the best way to perform this. Maybe regex?

I already tried to play with explode() and implode(), but no success – I have no creativity enough to explore their best.

1 Answer 1

1
<?php
$src = array (
    'item_name_1' => 'GTA V',
    'item_quantity_1' => 4,
    'item_price_1' => 5990,
    'item_name_2' => 'Watch_Dogs',
    'item_quantity_2' => 1,
    'item_price_2' => 5990,
);

$dest = array();

foreach($src as $k => $v) {
  $sfx = preg_replace('/.*?_([0-9]+)$/', '$1',$k);
  $dest[$sfx][$k] = $v;
}

print_r($dest);
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.