Alix Ohrt
Alix Ohrt

Reputation: 199

Array notation with Salesforce Apex

In Salesforce Apex, I'm trying to create a multi-dimensional array that I can later serialize into JSON.

In PHP I would do it as such:

$form['fields'][$element[1]][$element[2]] = $data;

But I can't seem to find a way to easily do this with Apex...can anyone guide me in the right direction?

Upvotes: 2

Views: 578

Answers (2)

Alix Ohrt
Alix Ohrt

Reputation: 199

Thing I got it sorted after using the following code:

Map<String, Map <String, String>> fieldsMap = new Map<String, Map <String, String>>();

if(fieldsMap.containsKey(keyArray[1])){
    fieldsMap.get(keyArray[1]).put(keyArray[2], m.get(key));
}

else {
     Map<String,String> newMap = New Map<String,String>();
     newMap.put(keyArray[2], m.get(key));

     fieldsMap.put(keyArray[1], newMap);
}

Thanks for pointing me in the right direction Daniel!

Upvotes: 1

Daniel Ballinger
Daniel Ballinger

Reputation: 13537

You can have a List of Lists in Apex. This allows you to create jagged arrays (as you need to ensure the each sub list is of the required size).

List<List<String>> fruit = new List<List<String>> {
    new List<String>{'banana', 'apple', 'pear'},
    new List<String>{'grape', 'tomato', 'orange'},
    new List<String>{'peach', 'plum', 'strawberry'}
};

System.debug(fruit[1][2]);

You may also want to consider a Map<String, List<String>> if you want to find sub lists by key.

Upvotes: 1

Related Questions