2

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So in my case I am looping through form input in the apex controller and compiling these arrays. So I need to be able to add key/value pairs based on a label. So how do I had directly onto a list in the map you provided given a string for the parameter?
1

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!

Comments

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.