John Davidson

How to flatten multi dimensional object which is in fact array in php?

0 comments
Message:


So, i have multi dimensional - multi object array which looks something like this(just a snippet):


array(1) {
[0]=>
object(Justimmo\Model\Realty)#14 (136) {
["id":protected]=>
int(103xxx757)
["propertyNumber":protected]=>
string(10) "3108xx6"
["title":protected]=>
string(62) "Ruhige 3-Zimmer mit Freifläche in ..."
["teaser":protected]=>
NULL
["proximity":protected]=>
string(4) "Wien"
["description":protected]=>
["additionalCosts":protected]=>
array(1) {
["betriebskosten"]=>
object(Justimmo\Model\AdditionalCosts)#24 (8) {
["name":protected]=>
string(14) "Betriebskosten"
["net":protected]=>
float(140)
["gross":protected]=>
float(154)
["vat":protected]=>
float(10)
["vatType":protected]=>
string(7) "percent"
["vatValue":protected]=>
float(14)
["vatInput":protected]=>
float(10)
["optional":protected]=>
bool(false)
}
}
...........

How can i flatten it to be one dimensional array so i can process it further?


Thanks.



My Answer:
> To flatten a multi-dimensional array in PHP, you can use a recursive function to iterate through each element and flatten it into a single-dimensional array. Here's an example code snippet to achieve this:

php
function flattenArray($array) {
$result = [];
foreach ($array as $value) {
if (is_array($value)) {
$result = array_merge($result, flattenArray($value));
} else {
$result[] = $value;
}
}
return $result;
}

$multiDimensionalArray = [
[1, 2, [3, 4]],
[5, [6, 7]],
8
];

$flattenedArray = flattenArray($multiDimensionalArray);

print_r($flattenedArray);


This code will output a flattened array `[1, 2, 3, 4, 5, 6, 7, 8]` from the given multi-dimensional array. You can modify the function according to your specific array structure if needed.

Rate this post

4 of 5 based on 5376 votes

Comments




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