简体   繁体   中英

Convert some values from two dimensional array to one dimensional array

array (size=2)
  0 => 
    array (size=4)
      'id_tax' => string '1' (length=1)
      'rate' => string '21.000' (length=6)
  1 => 
    array (size=4)
      'id_tax' => string '2' (length=1)
      'rate' => string '15.000' (length=6)

all what I want is array

1 => 21
2 => 15

what is tehe best function for doing that?

$newArray = [];
foreach($array as $v){
    $newArray[] = $v['rate'];
}
print_r($newArray);

If you need corrispondeces between id_tax and rate , then just do, as sgt pointed out:

$newArray[$v['id_tax']] = $v['rate'];

try this:

$newArray = array();


foreach($array as $value) {
    $newArray[$value['id_tax']] = $value['rate'];
}

As of PHP >= 5.5 you can use array_column to do the dirty work for you

Get column rate, indexed by the "id_tax" column

$newArray = array_column($array, 'rate', 'id_tax');

print_r($newArray); 

Prints

Array
(
    [1] => 21.000
    [2] => 15.000
)

This should work for you:

<?php

    $array1 = array(array("id_tax" => "1", "rate" => "21.000"), array("id_tax" => "2", "rate" => "15.000"));
    $array2 = array();

    foreach($array1 as $k => $v){
        $array2[$v['id_tax']] = $v['rate'];
    }

    var_dump($array2);


?>

Output:

array(2) {
  [1]=>
  string(6) "21.000"
  [2]=>
  string(6) "15.000"
}
$myArray = array();
foreach ($array as $k => $v){
    $myArray[$v['id_tax']] = $v['rate'];
}

so you have the result :

1 => 21
2 => 15

This below snippet should work fine for you - It's very simple

$array1 = array(array("id_tax" => "1", "rate" => "21.000"), array("id_tax" => "2", "rate" => "15.000"));

print_r(array_combine(array_column($array1 ,'id_tax' ), array_column($array1,'rate')));

Php version : 5.4.0 and ownwards

Output :

Array ( [1] => 21.000 [2] => 15.000 )

Thanks,

Sapan Kumar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM