Skip to content

Instantly share code, notes, and snippets.

@parweb
Last active November 22, 2016 16:14
Show Gist options
  • Save parweb/26988b8125226dd7f3ecb20d5e541075 to your computer and use it in GitHub Desktop.
Save parweb/26988b8125226dd7f3ecb20d5e541075 to your computer and use it in GitHub Desktop.
Do you know a better way ?
<?php
$input = array(
'data' => array(
'vehicles' => array(
0 => array(
'id' => '782',
'vin' => 'VF7SA9HD8DW660669',
'equipments' => array(
0 => array(
'id' => '18698',
'type' => 'includes',
'name' => 'Moulures latérales chromées',
) ,
) ,
) ,
) ,
) ,
);
<?php
$input = [ .... ]; // see the file : input.php
// rcollect for recursivly collect (or transform) array to nested collections
// do you see a better way ?
function rcollect( array $array, $previous_key = 0 ) {
foreach ( $array as $key => $value ) {
if ( is_array( $value ) ) {
$value = rcollect( $value, $key );
$array[$key] = $value;
}
}
if ( is_int( $previous_key ) || ( count( array_keys( $array ) ) && !is_int( array_keys( $array )[0] ) ) ) {
return (object)$array;
}
else {
return collect( $array );
}
}
// $output
object(stdClass)#490 (1) {
["data"]=>
object(stdClass)#489 (1) {
["vehicles"]=>
object(Illuminate\Support\Collection)#496 (1) {
["items":protected]=>
array(1) {
[0]=>
object(stdClass)#542 (3) {
["id"]=>
string(3) "782"
["vin"]=>
string(17) "VF7SA9HD8DW660669"
["equipments"]=>
object(Illuminate\Support\Collection)#545 (1) {
["items":protected]=>
array(4) {
[0]=>
object(stdClass)#518 (3) {
["id"]=>
string(5) "18698"
["type"]=>
string(8) "includes"
["name"]=>
string(29) "Moulures latérales chromées"
}
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment