0

I've a multidimensional array of some arrays, in which the first values are ordered and included in a specific range.

Example:

A1=[[0,a],[3,b],[5,c],[6,a],[9,c]] 

in which A1[i][0] are in range (0,10)

How can I obtain an array where, if the first value (A1[i][0]) isn't a value present in the first array, e.g.

A1[i][0]==2

I insert an array with that value in the right position, with a specified second value (example A)?

Example of output i want:

A1=[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]
3

1 Answer 1

2

This will help

$A1 = [[0,'a'],[3,'b'],[5,'c'],[6,'a'],[9,'c']];
foreach($A1 as $A2) $A3[] = $A2[0];//make a new array contain keys of the first array.
for($i=0;$i<=9;$i++){
    if(!in_array($i, $A3)){
        $A1[] = [$i, 'A']; //check if the key not exist, make a new array with key who does not exist.
    }
}
asort($A1);//sort the new element inside the array
print_r($A1);

output is,

[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]
Sign up to request clarification or add additional context in comments.

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.