I want to covert below array into single array. This is the my array code as below:
Array
(
[0] => Array
(
[label] =>
[value] =>
)
[1] => Array
(
[value] => 4
[label] => 0.5
)
[2] => Array
(
[value] => 5
[label] => 0.6
)
)
Want below result:
Array(
'4' => '0.5',
'5' => '0.6',
);
3 Answers 3
Try this:
$single_array = array();
foreach($array as $keys => $values){
$single_array[$values['label']] = $values['value'];
}
Use can use filter like not empty or null as you want.
Comments
Try this:
$array = array(
array('value' => '', 'label' => ''),
array('value' => 4, 'label' => 0.5),
array('value' => 5, 'label' => 0.6)
);
$new_array = array();
foreach($array as $item_array){
if(!empty($item_array['value'])){
$new_array[$item_array['value']] = $item_array['label'];
}
}
print_r($new_array);
Comments
You can make use of following functions :
array_column() — Return the values from a single column in the input array
array_combine() — Creates an array by using one array for keys and another for its values
array_filter() — Filters elements of an array using a callback function, If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.
Script
akshay@db-3325:/tmp$ cat test.php
<?php
$array = array(
array('value' => '', 'label' => ''),
array('value' => 4, 'label' => 0.5),
array('value' => 5, 'label' => 0.6)
);
/* make use of array_column and array_combine */
print_r( array_combine( array_column($array, 'value'), array_column($array, 'label') ) );
/* to remove empty elements use array_filter */
print_r( array_filter( array_combine( array_column($array, 'value'), array_column($array, 'label') ) ) );
?>
Output
akshay@db-3325:/tmp$ php test.php
Array
(
[] =>
[4] => 0.5
[5] => 0.6
)
Array
(
[4] => 0.5
[5] => 0.6
)
$result = array_column($originalArray, 'label', 'value');