Playing
01. Flattening A PHP Multidimensional Array

Episodes

0%
Your progress
  • Total: 12m
  • Played: 0m
  • Remaining: 12m
Join or sign in to track your progress

Transcript

00:00
So if you need to flatten a multidimensional array in PHP, we're going to be looking here at two different methods to do this.
00:08
Now, the first one is going to be a little bit more verbose. It's going to involve looping through the array to actually sort it and create a new array as we need. And the second is going to use some standard PHP classes,
00:21
which is going to give us a lot less code that we work with. It's a little bit more complicated to understand because we can't explicitly see what's going on.
00:30
But both of these methods work pretty well to flatten a multidimensional array. So you can see the result of it just here. This is one of the methods.
00:38
They both obviously come out with the same result. And I've chosen to create an array that was some kind of validation. And this contains different keys with an array within them
00:50
keys or within them values. So let's take a look at the first method. Then we'll jump straight onto the second method. And you can choose which one you want to use.
00:59
Either way, it's a good way to go through this just to learn about how this can be done if you ever do need to do this in the future. So let's crack on with the first method then.
01:08
So the first method involves creating a basic function, which is going to loop through all of the items within the array that we provide. And if it finds that there's another array within any
01:19
of these values or these keys, it will go ahead and it will call itself again. And that allows us to have an unlimited amount of nesting. And then we can build up a new array
01:30
and then return this from this function. It sounds a little bit more complicated than it actually is. So let's go ahead and start building it and just
01:37
see what this looks like. So we're going to define the function called flattenArray. And we need to work out what's going to be passed into this array.
01:47
Now initially, all we're going to need to pass in is an array of items. The reason I'm type hinting this is because if anything else other than an array is passed in,
01:57
this will give us an error. We want to make sure that this is actually an array. So if you don't already have an example array, go ahead and build something similar to this
02:06
just so you have some kind of data to work with. So the next thing then is within here, we want to loop through these items. So we're going to create a forEach.
02:15
And for each of these items loop, we're going to call this item. So we can now work with this item in here. Let's just do a quick var dump on item
02:25
just to see what we get out. And you can see here we get, once we call the function, so let's just call flattenArray, which is this variable up here, we get the following.
02:42
So we've got three arrays here. So as we go through this main array, the first thing we want to do is check if this key here, the value of this key here, is an array.
02:54
Because technically we could have something else down here which is just a string and it doesn't contain any value, doesn't have an array within it. So we want to include them values as well.
03:05
So in here, what we're going to do is we're going to check if that item is an array. And let's just go ahead and var dump the result of flattenArray just so we can see the new output.
03:21
So if this item is an array, so this is an array, this is an array, and this is an array, we could just bring back our single string value just here. Then what do we need to do if this item is an array?
03:38
Well, we need to define a new variable called flattened, which technically isn't going to be a new variable because we're going to pass it in with our arguments just up here.
03:48
And we're going to call this function. So it's going to call itself. I'm going to pass in the item and the flattened array that we currently have.
03:59
And this flattened array needs to be passed in and also defined here as an empty array. So let's just go through this once more. When we originally call this flattenArray function,
04:14
we pass in an array here. And we also have a value, an argument called flatten, which is by default an empty array. Now for each of these loops, if this happens to be an array,
04:26
which it is, we're going to call the same function. So we're going to call this function. And we're going to pass in that particular item, which is this here.
04:36
And that allows it to run all over again and then check if there are any arrays within this array. So it's going to obviously work with a multidimensional array. That's the point of this.
04:47
But what we're also going to do is we're going to pass in this flattened variable, which for the first loop will be an empty array. And then we're going to assign this to it again.
04:58
We're going to assign the return value of this to this flattened variable. Now what that's going to do is it's going to keep adding to that variable.
05:07
But at the moment, it won't. All we're doing is we're assigning the return value of this. Now what we're going to do outside of this if statement
05:17
is we're going to actually append to the array. And we use the square brackets like this just after the variable to do this. And that's going to be item.
05:26
Now this will be appended to this array here if this is not an array. So let's say we go on the first loop. This outer thing is an array.
05:34
So this array here variable is an array. So when we go through each of these items, so let's say we get to name, this is an array. So because it is an array, we're
05:45
going to call it again with that item. And that first item will be this. That isn't an array. It's a string value.
05:52
So we skip this if statement and append that string value to this flattened array here. The second time it loops, it will look for this. So this is a string again.
06:03
So it will append this again. It will skip this if statement. If we did happen to have an array in here, so key, and have another array with something in,
06:15
then what's going to happen is this if statement is going to return or is going to evaluate to true because we have another array in here. It will call it again.
06:24
It will find this string the next time around. It will skip this if statement and add it to here. So if that still doesn't make sense, write the code out anyway.
06:32
But just take a while to go through this. Maybe put some var dumps in and just see what kind of data that you're getting back here. So now that we've done that, we're
06:40
not actually returning anything from this function. So we're going to go ahead and return that flattened array or that flattened variable, which is an array in itself. So now what's going to happen is when
06:53
we do a var dump on flattened array, it's going to obviously take in this array, loop through it as I've just explained, and it will append to this flattened variable
07:02
here and then return it at the end. So we'll get out the following. Oops, let's just go ahead and modify this to continue if that is the case, because we
07:15
don't want to go ahead. And if this is an array, we don't want to go ahead and append it. That's what's happening here at the moment.
07:20
So we get the following. So that continue statement is really important, because if it is an array, we don't want to go ahead and append it to our flattened array, which
07:30
will contain only string or integer or float values. So that's the first method. As you can see, a little bit more verbose than we would probably like.
07:41
But it does work. You can see that we've got this something else string here at the end, which is just floating around at the bottom of this array in the last key.
07:48
And we've preserved the key values, because remember, we're building up a new array. And this works perfectly. However, there is another method that we
07:59
can use, which is a little bit simpler to write. It's less easy to understand in terms of just looking at the code. So it will look a little bit more complicated.
08:10
But I will try my best to explain as we go. So let's head over to the second file then, which is doing nothing at the moment. And let's go ahead and start to look at how we can do this.
08:23
So I'm going to create a flattened variable here. And I'm going to create a new recursive array iterator instance. Let's just change that iterator.
08:37
So we have a recursive array iterator. This is a standard PHP class that allows us to iterate over multidimensional arrays, or just basically iterate over them.
08:50
So we need to pass in array here. So let's do a var dump on flattened and see what we've got. And let's give that a refresh.
09:00
So we've got an object now, a recursive array iterator. And you can see here that we've got properties which correspond to the keys within that original array.
09:12
So now what we want to do is I'm just going to, for the sake of this, keep creating a new flattened variable and just repassing that in.
09:20
But we'll tidy this up at the end. We now want to, again, use a standard PHP class called recursive iterator iterator, which sounds really complicated.
09:29
But this is now going to allow us to iterate over this recursive array iterator. So let's go ahead and create this. So recursive iterator iterator.
09:43
And we pass in that recursive array iterator object. So now when we go ahead and do a var dump on flattened, we're not actually going to see anything here. We just have this recursive iterator iterator.
09:57
We need to use a function called iterator to array, which will convert or basically change this to an array. So now that we've allowed ourselves to recurse over this iterator, we
10:12
can go ahead and come up with our final result. So let's go ahead and say flattened equals iterator to array. And we're going to pass in that flattened array here.
10:24
Now for the second argument, we're going to say false. And this is because we don't want to use the iterator keys as the index. That's pretty important.
10:36
So now let's go ahead and var dump on flattened and see what result we get. And you can see we've now got exactly the same result as we had before, minus some of the other things we added.
10:48
So we can have an inner array here with some value. And then we can have just a string value hanging around at the end if we want. And we come up with exactly the same result in a lot less code.
11:03
But now let's go and just tidy this up, because you are not going to want to do this within an application, keep defining these variables over and over again
11:12
and passing them through. It gets a little bit complicated. So what we want to do then is we want to basically take this. And instead of referencing that variable
11:23
we originally created, let's just pull this down a couple of lines and paste it in here. And it still works in exactly the same way, but it just makes it look a little bit tidier.
11:32
And then we can even go as far as to say, let's wrap the whole thing here, passing in these values to this iterator to array function. And then we have our false value at the end.
11:46
So if we just remove that, we have this all nice and tidy now. And when we refresh, we get exactly the same result. So there are just a couple of ways
11:56
that we can iterate through and squash, if you like, or flatten a multidimensional array. The first one being a little bit more verbose, having to loop through and call a function again.
12:09
And the second one using some standard PHP classes to make this a lot shorter, a little bit harder to understand when you originally look at it. But it does the job perfectly.
1 episode 12 mins

Overview

A couple of methods you can use to flatten a multidimensional array with PHP. The first method looks at a more verbose method of looping through array items and self calling a function/method, and the second looks at using standard PHP classes to make it a bit cleaner.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!