0

So I have been looking and looking online to figure out how to make a two dimensional array. Like I kinda understand a one line linear array. But when I look online all I see is a bunch of code that I don't even understand what each component of the code does. Thanks for whoever answers.

Can you please explain important parts of the code to me and there function.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Lifetake
  • 191
  • 4
  • 11

2 Answers2

3

A multidimensional array is just a special case of an associative array in bash 4:

# Make myarray an associative array
declare -A myarray 

# Assign some random value
myarray[3,7]="foo"

# Access it through variables
x=3 y=7
echo "${myarray[$x,$y]}"

It works because "3,7" is just a string like any other. It could just as well have been "warthog" or "ThreeCommaSeven". As long as everything else in your code turns the indices 3 and 7 into the string "3,7", it'll work just like a multidimensional array.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • 1
    would't this still be linear though @that other guy – Lifetake Feb 27 '13 at 00:57
  • so what would be the output of this 'foo'? So how does that make it 2d ? Can you give a small ex with output please. Thanks sorry for my no understanding @that other guy – Lifetake Feb 27 '13 at 01:02
  • This is as good a way as any to implement a multidimensional array. If what you are really looking for is an array-of-arrays, where something like `${x[2]}` is another array, then `bash` is not the language for you. It's possible, but it quickly gets ugly, as you have to fake it with indirect parameter expansion and/or `eval`. – chepner Feb 27 '13 at 01:11
  • 1
    @Lifetake This is a complete example, and it outputs `foo`. It's 2D because you index it with two integer variables, just like a 2D array in any other language. It's not linear because no bash arrays are ever linear, they're always sparse. – that other guy Feb 27 '13 at 16:26
2

If you want to list the elements without knowing in advance their number, a very handy solution:

a=()
a+=( Mexico,2000 )
a+=( Canada,3000 )

for row in ${a[@]};
do
    echo place: ${row%%,*} airplanes: ${row##*,}
done
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Alex
  • 15
  • 2