skip to Main Content

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.

3

Answers


  1. $resultArr = [];
    foreach ($org_array as $one){
      $resultArr[ $one["offer_id"] ] = $one["quantity"];
    }
    
    // $resultArr now contains your desired structure
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. <?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
    // )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search