0

I have this array:

$priceTableData = array(

    array('productId'=>1,'price'=>50,'discount'=>12),
    array('productId'=>2,'price'=>22,'discount'=>2),
    array('productId'=>3,'price'=>7,'discount'=>0),
    array('productId'=>4,'price'=>9,'discount'=>0),
    array('productId'=>5,'price'=>35,'discount'=>7),

);

and I want to get this array out of it:

array(5) { 
[1]=> int(12) 
[2]=> int(2) 
[3]=> int(0) 
[4]=> int(0) 
[5]=> int(7) 
}

and I used this custom method to do so,

function getDiscounts(array $priceData){

    $result = array();

    foreach ($priceData as $array){

        $result[$array['productId']] = $array['discount'];

    }
    return $result;
}

then I used it as this:

var_dump(getDiscounts($priceTableData));

my question is: is there a native way of doing so, rather than having a custom function for it?

Thanks.

0

3 Answers 3

2

If you're using PHP 5.5 you can use array_column():

 $discounts= array_column($priceTableData , 'discount');

Demo

Since it was brought up in the comments I will also offer that if your array keys are defined by the product ID you should use the third parameters from array_column() to specify the productId as the keys in your new array:

$discounts= array_column($priceTableData , 'discount', 'productId ');

Demo

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

5 Comments

what if the id's are not in sequence?
They didn't specify that was a factor in their desired results. In their specific case as asked in their question this code will serve their purposes.
$result[$array['productId']] = $array['discount']; they are using the id as the key
thanks I was not aware of such a function, can you tell me where I can find a list of the new functions in 5.5?
2

you can use array_column which is introduced in PHP 5.5 like so

$result = array_column($priceTableData, 'discount','productId');

print_r($result);

Comments

2

if older version of php.

    $result = array_map(function($sub)
 { return $sub['discount']; }, $priceTableData);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.