0

Currently I am having an array like this

$myAllProducts= array(
           0=> array(
               'productName' => "Classmate",
               'productId' => 2
           ),
            1=>array(
                'productName' => "tata",
               'productId' => 3
            ),
            2=>array(
                'productName' => "abcd",
               'productId' => 4
            ),
            1=>array(
                'productName' => "pen",
               'productId' => 7
            ),
        )

And I want to convert it to an array like

array('Classmate'=>2,
'tata'=>3,
'abcd'=>4,
'pen'=>7)

I am doing it like this

$productList=array();
foreach($myAllProducts as $record)
            {
                $productsList[$record['productName']]=$record['productId'];
            }

Question:- Although I am successfully getting the desired result using my loop but I want to know if it could be done using any built in function or in a much better way?

1 Answer 1

5

If you're using PHP >= 5.5, then you can use the new array_column() function

$productList = array_combine(
    array_column(
        $myAllProducts,
        'productName'
    ),
    array_column(
        $myAllProducts,
        'productId'
    )
);

or (even simpler)

$productList = array_column(
    $myAllProducts, 
    'productId', 
    'productName'
);
Sign up to request clarification or add additional context in comments.

3 Comments

sorry but i am using 5.3 :(
There's a userland implementation of array_column() available at benramsey.com/blog/2013/07/… which would work with earlier versions than 5.5 - but your simple loop is the easiest way of doing it before array_column() was introduced into PHP core
thanks for letting me know about array_column() sir.

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.