0

I have a single array. I'm posting as JSON because that's my API output.

[
  {
    "compId": 26,
    "addonId": "1",
    "addonRate": "32"
  },
  {
    "compId": 26,
    "addonId": "2",
    "addonRate": "51"
  },
  {
    "compId": 7,
    "addonId": "1",
    "addonRate": "11"
  },
  {
    "compId": 7,
    "addonId": "2",
    "addonRate": "12"
  }
]

And I want convert that array so that I can get the following output:

[
  {
    "addonId": "1",
    "companies": {
        "compId": 26,
        "addonRate": "32"
      },
      {
        "compId": 7,
        "addonRate": "11"
      }
  },
  {
    "addonId": "2",
    "companies": {
        "compId": 26,
        "addonRate": "51"
      },
      {
        "compId": 7,
        "addonRate": "12"
      }
  }
]

So far I'm able to extract distinct compId and addonId. But then I want add those companies in each addons and the respective rate in the sub array.

Any help would be great! Thanks

2
  • you can use PHP to loop it Commented Jan 20, 2016 at 5:16
  • @SIDU I gave many try but so far as I said could only extract distinct compId and addonId into separate arrays. Any hint how do add the sub comp array into addon array with respective value? Commented Jan 20, 2016 at 5:20

1 Answer 1

1

Have you tried something like

$newArray = array();
foreach ($startingArray as $row) {
    if (!isset($newArray[$row['addonId']])
        $newArray[$row['addonId']] = array(
            'addonId'=>$row['addonId'],
            'companies'=>array()
        );
    }
    $newArray[$row['addonId']]['companies'][] = array(   
        "compId"=> $row['compId'],
        "addonRate"=> $row['addonRate']
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

HOLY! Just needed that simple classic if(!isset) statement. Just one correction "compId"=> $newArray[$row['compId']] would be "compId"=> $row['compId']. Thanks ALOT!
Fixed. Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.