Mamey
Mamey

Reputation: 95

How to store specific data from a multi-dimensional array into a variable

I have a multidimensional array like this one:

coeficiente VARCHAR[2][2];

What i have stored in this array is this information:

{{"uwu","2"},{"owo","5"}}

I have another 2 variables called:

variable1 VARCHAR;
variable2 VARCHAR;

I want to save the "2" into the variable1, and the "5" into variable2 from this multidimensional array content example.

How can i do that?

I was thinking in maybe a for loop, but i still dunno how iterate inside of an ARRAY[][] structure in plpgsql.

The closest examples I could reach in internet were:

stack overflow. But they store an array out of a multidimensional array. I only need to get the variable inside of it.

Postgres documentation. But it doesn't explain how to get inside of one specific "slot".

Upvotes: 0

Views: 116

Answers (2)

user330315
user330315

Reputation:

Maybe I am missing something, but:

variable1 := coeficiente[1][2];
variable2 := coeficiente[2][2];

will do what you want.

do
$$
declare
  coeficiente VARCHAR[2][2] := '{{"uwu","2"},{"owo","5"}}';
  variable1 VARCHAR;
  variable2 VARCHAR;  
begin
  variable1 := coeficiente[1][2];
  variable2 := coeficiente[2][2];
  
  raise notice 'var1=%', variable1;
  raise notice 'var2=%', variable2;
end;
$$  

Will output:

var1=2
var2=5

Upvotes: 1

senior_freshman
senior_freshman

Reputation: 181

You can loop over a two-dimensional array by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other.

Upvotes: 0

Related Questions