0

i have created bellow array

 businesscommercialArray =  {
 40E: {
       id: 94,
       swift_code: "40E",
       status: 1
 },
 43P: {
      id: 106,
      swift_code: "43P",
      status: 2,
      note: "Allowed (INSTEAD OF EXISTING)"
      }
 },
 27: {
      id: 106,
      swift_code: "27",
      status: 2,
      note: "Allowed"
      }
 }

i trying to loop through this array and if the status found as 2 means there is a note added. from there i want to take the key and note values to new array. like bellow

$finalarray =   {
  swift_code: "40E",
  note: ""
},
{
  swift_code: "43P",
  note: "Allowed (INSTEAD OF EXISTING)"
},
{
  swift_code: "27",
  note: "Allowed"
}

so far i managed to loop though it but not able to access the key and values

foreach($businesscommercialArray as $key => $values) { 
                    foreach($values as $key => $value)
                    {   
                      print_r($value);
                    }                    
                }

2 Answers2

1

First you should convert this JSON to a PHP array:

<?php
$businesscommercialArray = json_decode('{
    "40E": {
        "id": 94,
        "swift_code": "40E",
        "status": 1
    },
    "43P": {
        "id": 106,
        "swift_code": "43P",
        "status": 2,
        "note": "Allowed (INSTEAD OF EXISTING)"
    },
    "27": {
        "id": 106,
        "swift_code": "27",
        "status": 2,
        "note": "Allowed"
    }
}', true);

Then iterate over it and mount your final array:

$finalArray =  [];
foreach ($businesscommercialArray as $value) {
    var_dump($key, $value);
    $finalArray[] = [
        'swift_code' => $value['swift_code'],
        'note' => $value['note'] ?? '',
    ];
}
print_r($finalArray);
0

You can use array_map() to loop through the array and create the new arrays from each value.

$finalarray = array_map(function($value) {
    return [
        'swift_code' => $value['swift_code'],
        'note' => $value['status'] == 2 ? $value['note'] : ''
    ];
}, $businesscommercialArray);
Barmar
  • 741,623
  • 53
  • 500
  • 612