2

I have 2 arrays as below.

$keys = [1,2,3,4-1,99,1,2,3,4-1,4-2,4-3,99,1,2,3,4-1,4-2,99]
$values = [a,b,c,d,x,a1,b1,c1,d1,e,g,x,a2,b2,c2,d2,e,x]

I want to combine into an array like:

$result = array(
  [0]=>array(1=>a,2=>b,3=>c,4-1=>d,99=>x),
  [1]=>array(1=>a1,2=>b1,3=>c1,4-1=>d1,4-2=>e,4-3=>g,99=>x),
  [2]=>array(1=>a2,2=>b2,3=>c2,4-1=>d2,4-2=>e,99=>x
);

The rule is break anytime $key=99. Currently, I tried to use array_chunk but the syntax only allows me to chunk the array by the number of unique keys, which is not constant in my example. Any advice?

1
  • Add what you tried. $keys and $values are not arrays!! Commented Sep 12, 2017 at 6:33

3 Answers 3

1

You need to write a custom script which combines these two arrays by your logic.

You need to fetch each key from the $keys array and combine it with the same element by position from the $values array.

Example:

<?php
$keys = ['1', '2', '3', '4-1', '99', '1', '2', '3', '4-1', '4-2', '4-3', '99', '1', '2', '3', '4-1', '4-2', '99'];
$values = ['a', 'b', 'c', 'd', 'x', 'a1', 'b1', 'c1', 'd1', 'e', 'g', 'x', 'a2', 'b2', 'c2', 'd2', 'e', 'x'];

$i = 0;
$result = [];
foreach ($keys as $index => $key) {
    if (empty($result[$i]))
        $result[$i] = [$key => $values[$index]];
    else
        $result[$i][$key] = $values[$index];

    if ($key == 99)
        ++$i;
}

print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use foreach loop to achieve this

$keys = ["1","2","3","4-1","99","1","2","3","4-1","4-2","4-3","99","1","2","3","4-1","4-2","99"];
$values = ["a","b","c","d","x","a1","b1","c1","d1","e","g","x","a2","b2","c2","d2","e","x"];
$new_array = array();
$split_at = "99";
$i = 0;
foreach ($keys as $key => $value) {
    $new_array[$i][$value] =$values[$key];

    if($split_at == $value){
     $i++;
    }
}

print_r($new_array);

DEMO

Comments

0

Instead of conditionally incrementing a counter to determine where data gets pushed into an array, row data can be populated by pushing references into the result array.

Code: (Demo)

$result = [];
foreach ($keys as $i => $k) {
    if (!isset($ref)) {
        $result[] = &$ref;
    }
    $ref[$k] = $values[$i];
    if ($k == 99) {
        unset($ref);
    }
}

var_export($result);

If you want to maintain a counter variable, that can look like this: (Demo)

$counter = 0;
$result = [];
foreach ($keys as $i => $k) {
    $result[$counter][$k] = $values[$i];
    if ($k == 99) {
        ++$counter;
    }
}

var_export($result);

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.