1

To group data, every time there's a "new person" as below, I want to add their info to that temporary array and reset that array to null.

Before each "new person" array is set to null, I want to add that array to an array of people. An array of arrays.

How can I add one array into another?

$people = import-csv "./people.csv"

$h = @{}
$h.gettype()

$all_people

ForEach ($person in $people) {
  $new_person
  if ($person -match '[0-9]') {
    Write-host $person
  }
  else { 
    write-host "new person"
    write-host $person
  }
}

output:

thufir@dur:~/flwor/people$ 
thufir@dur:~/flwor/people$ pwsh foo.ps1 

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}

thufir@dur:~/flwor/people$ 

I have something like this:

$people = import-csv "./people.csv"

$all_people
$new_person = "new","person"

$new_person.GetType()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    $new_person.Add($person)
  }
  else { 
    write-host "new person"
    write-host $person
    #$new_person = null
    $new_person = "new","person"
  }
}
3
  • I think the question was so wrong there's no real answer. The solution is to use objects properly. But, yes, valuable :) Commented Feb 15, 2020 at 17:22
  • 1
    Yes, it is not impossible but there are several pitfalls going down this rabbit hole as PowerShell tends to unroll embedded arrays and singletons. Commented Feb 15, 2020 at 17:29
  • well, hopefully the question will at least benefit someone else as well :) Commented Feb 15, 2020 at 17:35

2 Answers 2

1

Powershell doesnt provide a good functionality to create an array of array with use of basic arrays.

What you can do use use an array of hashtable or PsCustomObjects to create yourself an array of arrays.

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

1 Comment

yes, I think I'll create an object or class called "person". doh.
0

Yes you can create array of arrays.

Example we create 3 arrays like

$a = 1..5
$b = 6..10
$c = 11..15

Now we can add them in another array $d

$d = $a,$b,$c

Now we can access them like:

$d[0]
# Output 
# 1
# 2
# 3
# 4
# 5
$d[0][2]
# Output is $a arrays 3rd element

4 Comments

Can you provide an example of how you would go about adding a new element to $d after its been created ?
Using the + operator @Jawad.
Did you try it, my point was it doesnt work. Do try, $d += $a then try to access the last item
I was telling about explicitly adding to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.