0

How to join lone elements of an array into the arrays within an array by order. Let's say I have the following array:

array:6 [
  0 => array:2 [
    "id" => 2
    "type" => "studio_apartment"
  ]
  1 => array:2 [
    "id" => 3
    "type" => "one_bedroom"
  ]
  2 => array:2 [
    "id" => 10
    "type" => "two_bedroom"
  ]
  3 => "20000"
  4 => "30000"
  5 => "40000"
]

Is it possible to get these lone elements in the array into the arrays above them? Such that the first lone element goes to the first array and so on. So that they can form something like this:

array:3 [
  0 => array:2 [
    "id" => 2
    "type" => "studio_apartment"
    "rent" => "20000"
  ]
  1 => array:2 [
    "id" => 3
    "type" => "one_bedroom"
    "rent" => "30000"
  ]
  2 => array:2 [
    "id" => 10
    "type" => "two_bedroom"
    "rent" => "40000"
  ]
  
]
0

1 Answer 1

1

Assuming the lone elements will always be last and there will always be the same number of lone elements as the others; you can remove the lone elements (last half), loop them and add to the remaining array with the proper key:

foreach(array_splice($array, count($array)/2) as $key => $value) {
    $array[$key]['rent'] = $value;
}
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.