Let me see
Let me see

Reputation: 5094

How to convert an array to a simpler form using php function

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?

Upvotes: 0

Views: 44

Answers (1)

Mark Baker
Mark Baker

Reputation: 212472

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'
);

Upvotes: 5

Related Questions