Home > Blockchain >  how to get array from given array in php
how to get array from given array in php

Time:01-31

I've array like this in php:

Array
(
    [0] => Array
        (
            [offer_id] => 62122
            [quantity] => 1
        )

    [1] => Array
        (
            [offer_id] => 62123
            [quantity] => 2
        )

    [2] => Array
        (
            [offer_id] => 62124
            [quantity] => 2
        )

)

I want to create new array from the above array like this:

Array
(
    [62122] => 1
    [62123] => 2
    [62124] => 2
)

and so on. Any help will be appreciated. Thanks in advance.

CodePudding user response:

There is a PHP function that can do this for you: array_column().

The first argument is the array.
The second argument is the key you want as value.
The third (optional) argument is which key should be used as index

$newArray = array_column($array, 'quantity', 'offer_id');

Here's a demo: https://3v4l.org/AANUO

CodePudding user response:

$resultArr = [];
foreach ($org_array as $one){
  $resultArr[ $one["offer_id"] ] = $one["quantity"];
}

// $resultArr now contains your desired structure

CodePudding user response:

<?php

$originalArray = [
    [
        "offer_id" => 62122,
        "quantity" => 1
    ], [
        "offer_id" => 62123,
        "quantity" => 2
    ], [
        "offer_id" => 62124,
        "quantity" => 2
    ]
];

$newArray = array_column($originalArray, 'quantity', 'offer_id');

print_r($newArray);

// Output : 
// Array
// (
//     [62122] => 1
//     [62123] => 2
//     [62124] => 2
// )
  •  Tags:  
  • php
  • Related