简体   繁体   中英

PHP - split one array into 2 array based on key value pair

one array of object =

[{
    "id": "5b2a4b0287bc2c082ebc2897",
    "test_name": "BSF",
    "test_type": "Pathology",
    "cost": "100"
}, {
    "id": "5b2a4ac63db998081e7f6c97",
    "test_name": "Brain & PNS",
    "test_type": "Radiology",
    "cost": "1000"
}, {
    "id": "5b2a4ac63db998081e22336c97",
    "test_name": "BPNS",
    "test_type": "Radiology",
    "cost": "1000"
}] 

I want to split this array of object into two separate array of object based on key value pair - "test_type"

O/p 1 st array

[{
    "id": "5b2a4b0287bc2c082ebc2897",
    "test_name": "BSF",
    "test_type": "Pathology",
    "cost": "100"
}]

2 nd array

[ {
    "id": "5b2a4ac63db998081e7f6c97",
    "test_name": "Brain & PNS",
    "test_type": "Radiology",
    "cost": "1000"
},{
    "id": "5b2a4ac63db998081e22336c97",
    "test_name": "BPNS",
    "test_type": "Radiology",
    "cost": "1000"
}] 

You can create temporary arrays:

$arr = json_decode($str, true);

foreach($arr as $a){
    if($a['test_type'] == 'Radiology'){
        $radiology_array[] = $a;
    }
    if($a['test_type'] == 'Pathology'){
        $pathology_array[] = $a;
    }
    ...
}

I believe this is JSON format.

Just use the old json_decode($variable) and assign each key to another variable.

$result = json_decode($variable);

$type = [];
foreach ($result as $item) {
    $type[$item->test_type][] = $item;     
}

This way, each test_type will have it's own key. Which could be used as one array for each test_type.

You can use array_column to make a flat array of the type which you the use as the matching array.
When you loop the matching array ($type) you can use array_intersect to get the subarrays as you wanted.

I place them in an associative array that can be extracted to new variables.

$arr = json_decode($json,true);
$type = array_column($arr, "test_type");

Foreach(array_unique($type) as $t){
   $new[$t] = array_intersect_key($arr, array_intersect($type, [$t]));
}
extract($new);
var_dump($Radiology, $Pathology);

https://3v4l.org/nj936

This method will only loop the unique count of types and will work even if you add a new type to the list like: https://3v4l.org/Jf0SE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM