2
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?

0

6 Answers 6

5
$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'];
Sign up to request clarification or add additional context in comments.

3 Comments

the key of new array will be the id_tax of the array.. :)
that produce Array ( [0] => 21.000 [1] => 15.000 )
I specify array what i need obtain im my question
3

try this:

$newArray = array();


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

Comments

3

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
)

Comments

1

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"
}

Comments

1
$myArray = array();
foreach ($array as $k => $v){
    $myArray[$v['id_tax']] = $v['rate'];
}

so you have the result :

1 => 21
2 => 15

Comments

1

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

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.