通过在PHP中读取不同的JSON数组元素来创建新的JSON

I have a JSON object that looks something like this

OBJECT $deals

[
  {
    "deal_id": 124563
    "merchant_id": 123
    "merchant_name": Merchant1
  }
  {
    "deal_id": 456789
    "merchant_id": 123
    "merchant_name": Merchant1
  }
  {
    "deal_id": 46646
    "merchant_id": 456
    "merchant_name": Merchant2
  }
]

What I am trying to do is this right now

$category_merchants = array();
foreach ($deals as $deal) {
  array_push($category_merchants, $deal->merchant_id, $deal->merchant_name)
}
$category_merchants = json_encode($category_merchants);

The new JSON object has all the merchants from the original JSON. Is there an easy way to just get the distinct merchants (merchant_name, merchant_id) in the new JSON with counts of how many times they were in the original JSON?

use array_map() like this:

array_map(function($v){return [$v->merchant_id, $v->merchant_name];}, $array);
  1. Convert json to array

    $array = json_decode($deals);

  2. loop array to get unique merchant name

    foreach($array as $key => $value) { $category_merchants[$value['merchant_id']] = $value['merchant_name']; $category_merchant_count[] = $value['merchant_id']; //this is to count number of merchant occurance }

  3. Convert category_merchants back to json

    $merchant = json_encode($category_merchants);

  4. Get number of merchant occurance

    print_r(array_count_values($category_merchant_count))

One way. Just use the merchant_id as the key and increment the count:

$deals = json_decode($json, true);

foreach ($deals as $deal) {
  if(!isset($category_merchants[$deal['merchant_id']])) {
      $category_merchants[$deal['merchant_id']] = $deal;
      $category_merchants[$deal['merchant_id']]['count'] = 1;
      unset($category_merchants[$deal['merchant_id']]['deal_id']);
  } else {
      $category_merchants[$deal['merchant_id']]['count']++;
  }      
}

If you need to re-index the array then:

$category_merchants = array_values($category_merchants);