0

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
  • Try this: $single_array = array(); foreach($array as $keys => $values){ $single_array[$values['label']] = $values['value']; } Commented Aug 28, 2017 at 14:58
  • 1
    $result = array_column($originalArray, 'label', 'value'); Commented Aug 28, 2017 at 14:59
  • @Nirbhav Gupta: Thanks your answer works for me thanks, please add this in answer I will up vote for this Commented Aug 28, 2017 at 15:07

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.