Reputation: 337
I'm having an array key-value pair. I need to create new array from this key and value pair. for eg
I tried with foreach loop
foreach($array as $key => $val){
// here i m getting key and value i want to combine key and value in single array
}
Array
(
'146' => Array
(
'sam' => Array (
'dex',
'max'
)
)
'143' => Array
(
'tim' => Array (
'thai',
'josh'
)
)
)
and the expected output is push key as first element
$out = [
[ 'sam', 'dex', 'max'],
[ 'tim','thai', 'josh']
];
Upvotes: 0
Views: 2722
Reputation: 17805
Code:
<?php
$arr = Array(
'146' => Array
(
'sam' => Array (
'dex',
'max'
)
),
'143' => Array
(
'tim' => Array (
'thai',
'josh'
)
)
);
$result = [];
foreach($arr as $key => $value){
$flat_data = [];
flattenArray($value,$flat_data);
$result[] = $flat_data;
}
function flattenArray($data,&$flat_data){
foreach ($data as $key => $value) {
if(is_array($value)){
$flat_data[] = $key;
flattenArray($value,$flat_data);
}else{
$flat_data[] = $value;
}
}
}
print_r($result);
Demo: https://3v4l.org/bX9R3
Since, we are passing a new array to collect the results as second parameter, this would perform better than returning an array of results on each function call and then doing an array merge(which would have made a bit inefficient).
This would work independent of the depth of levels.
Upvotes: 0
Reputation: 11642
You can use array-merge as:
foreach($array as $key => $val)
$out[] = array_merge([$key], $val);
Notice that in your example you also have another level of keys ("146", "143") -> you need to remove it before using this code.
Edited:
foreach($arr as $val) {
$key = key($val);
$out[] = array_merge([$key], $val[$key]);
}
Live example: 3v4l
Upvotes: 2
Reputation: 328
What about this?
$output = [];
foreach($array as $key => $val) {
$data = $val;
array_unshift($data, $key);
$output[] = $data;
}
Upvotes: 0