John Davidson

PHP how to join elements in an array by order

0 comments
Message:


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"
]

]


My Answer:
Yes, it is possible to achieve this by iterating through the original array and adding the lone elements to the arrays above them. Here is an example code snippet to achieve this:

php
$array = [
0 => [
"id" => 2,
"type" => "studio_apartment"
],
1 => [
"id" => 3,
"type" => "one_bedroom"
],
2 => [
"id" => 10,
"type" => "two_bedroom"
],
3 => "20000",
4 => "30000",
5 => "40000"
];

$newArray = [];
$index = 0;

foreach ($array as $key => $value) {
if (is_array($value)) {
$newArray[$index] = $value;
$newArray[$index]['rent'] = $array[$key + 3];
$index++;
}
}

print_r($newArray);


This code will output the desired result where the lone elements are added to the arrays above them.

Rate this post

4 of 5 based on 2442 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us