i have array look like this:
$arr=array(
'key1'=>'value1',
'key2'=>'value2',
0=>array(
'sub1_key1'=>'sub1_value1',
'sub1_key2'=>'sub1_value2',
),
'key3'=>array(
'sub2_key1'=>'sub2_value1',
'sub2_key2'=>'sub2_value2',
),
//....
);
how to converter array $arr to array look like this:
$arr=array(
'key1'=>'value1',
'key2'=>'value2',
'sub1_key1'=>'sub1_value1',
'sub1_key2'=>'sub1_value2',
'sub2_key1'=>'sub2_value1',
'sub2_key2'=>'sub2_value2',
//....
);
somebody can help me?
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
PHP | array_flip() Function This built-in function of PHP is used to exchange elements within an array, i.e., exchange all keys with their associated values in an array and vice-versa. We must remember that the values of the array need to be valid keys, i.e. they need to be either integer or string.
PHP: array_reverse() function The array_reverse() function is used to reverse the order of the elements in an array. Specifies the name of the array. Specify TRUE or FALSE whether function shall preserve the array's keys or not. The default value is FALSE.
array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys. Note that the values of array need to be valid keys, i.e. they need to be either int or string.
Try this out. This works for you hopefully.
This is not trivial, because you are going to reduce multi.dim. array to single one and also ignore the key of the first array.
I have tested the following code and it produces that result you have shown.
function ChangeArrayToSingleArray($array) {
if (!$array) return false;
$flat = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key=>$value)
$flat[$key] = $value;
return $flat;
}
var_dump(ChangeArrayToSingleArray($arr));
output is some thing like.
array (size=6)
'key1' => string 'value1' (length=6)
'key2' => string 'value2' (length=6)
'sub1_key1' => string 'sub1_value1' (length=11)
'sub1_key2' => string 'sub1_value2' (length=11)
'sub2_key1' => string 'sub2_value1' (length=11)
'sub2_key2' => string 'sub2_value2' (length=11)
$new = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) { // having nested loop to save keys and values into new array
$new[$k] = $v;
}
} else {
$new[$key] = $value; // leaving values intact
}
}
print_r($new); // returns Array ( [key1] => value1 [key2] => value2 [sub1_key1] => sub1_value1 [sub1_key2] => sub1_value2 [sub2_key1] => sub2_value1 [sub2_key2] => sub2_value2 )
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With