array multidimensional array php

Convert multidimensional array into single array

I have an array which is multidimensional for no reason

I want to convert this array into this form

Any idea how to do this?

20 Answers 20

This single line would do that:

The first argument is an array | The second argument is an array key.

Assuming this array may or may not be redundantly nested and you’re unsure of how deep it goes, this should flatten it for you:

If you come across a multidimensional array that is pure data, like this one below, then you can use a single call to array_merge() to do the job via reflection:

Just assign it to it’s own first element:

this is best way to create a array from multiDimensionalArray array.

For this particular case, this’ll do:

It’s basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.

none of answers helped me, in case when I had several levels of nested arrays. the solution is almost same as @AlienWebguy already did, but with tiny difference.

You can do it just using a loop.

array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.

If this was my code, I’d be using array_column() because it is direct and speaks literally about the action being performed.

Of course a couple of `foreach() loops will perform very efficiently because language constructs generally perform more efficiently than function calls.

Источник

PHP multidimensional array search by value

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

I tried making loops, but I want a faster executing code.

22 Answers 22

This will work. You should call it like this:

Based on angoru answer. In later versions of PHP ( >= 5.5.0 ) you can use one-liner.

If you are using (PHP 5 >= 5.5.0) you don’t have to write your own function to do this, just write this line and it’s done.

If you want just one result:

For multiple results

In case you have an associative array as pointed in the comments you could make it with:

If you are using PHP

In later versions of PHP (>= 5.5.0) you can use this one-liner:

Building off Jakub’s excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):

I know this was already answered, but I used this and extended it a little more in my code so that you didn’t have search by only the uid. I just want to share it for anyone else who may need that functionality.

Here’s my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.

Читайте также:  самый первый телефон сяоми

Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.

Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.

This second example shows you where a value (‘Taylor’) is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name ‘Taylor’ AND are employed).

Источник

How to remove duplicate values from a multi-dimensional array in PHP

How can I remove duplicate values from a multi-dimensional array in PHP?

18 Answers 18

Here is another way. No intermediate variables are saved.

We used this to de-duplicate results from a variety of overlapping queries.

Since 5.2.9 you can use array_unique() if you use the SORT_REGULAR flag like so:

Output

Keep in mind, though, that the documentation states:

array_unique() is not intended to work on multi dimensional arrays.

I had a similar problem but I found a 100% working solution for it.

Another way. Will preserve keys as well.

This will remove the duplicate names from array. unique by key

If «remove duplicates» means «remove duplicates, but let one there», a solution might be to apply the array_unique(. ) on the «identifier column» first and then to remove in the original array all the keys, that have been removed from the column array:

The user comments on the array_unique() documentation have many solutions to this. Here is one of them:

kenrbnsn at rbnsn dot com
27-Sep-2005 12:09

Yet another Array_Unique for multi-demensioned arrays. I’ve only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.

This function uses the serialize, array_unique, and unserialize functions to do the work.

if you need to eliminate duplicates on specific keys, such as a mysqli id, here’s a simple funciton

Bonus Points You can pass an array of keys and add an outer foreach, but it will be 2x slower per additional key.

A very easy and logical way to Unique a multi dimension array is as follows,

If you have array like this:

use foreach to solve this:

it will give you following result:

and if you want to rearrange the order of the keys,

This operation will give you arranged key values like this:

I hope this will clear everything.

if you have an array like this:

(users is the name of the array)

Читайте также:  Tiens казахстан чем занимается

and you want to delete duplicates. then:

can be a solution 😛

Lots of person asked me how to make Unique multidimensional array. I have taken reference from your comment and it helps me.

First of All, Thanks to @jeromegamez @daveilers for your solution. But every time i gave the answer, they asked me how this ‘serialize’ and ‘unserialize’ works. That’s why i want to share the reason of this with you so that it will help more people to understand the concept behind this.

I am explaining why we use ‘serialize’ and ‘unserialize’ in steps :

Step 1: Convert the multidimensional array to one-dimensional array

To convert the multidimensional array to a one-dimensional array, first generate byte stream representation of all the elements (including nested arrays) inside the array. serialize() function can generate byte stream representation of a value. To generate byte stream representation of all the elements, call serialize() function inside array_map() function as a callback function. The result will be a one dimensional array no matter how many levels the multidimensional array has.

Step 2: Make the values unique

To make this one dimensional array unique, use array_unique() function.

Step 3: Revert it to the multidimensional array

Though the array is now unique, the values looks like byte stream representation. To revert it back to the multidimensional array, use unserialize() function.

Источник

PHP Multidimensional Arrays

A multidimensional array is an array which stores another array at each index rather than storing a single value. In simple words, a multidimensional array is an array of arrays.

In general practice, associative array are stored inside multidimensional arrays.

Creating a Multidimensional Array

As we have already seen how to create an associative array, and multidimensional array being an array of arrays, will hold the associative arrays inside it.

Syntax for creating multidimensional array:

As we are dealing with array inside an array here, hence to access any information, we first need to reach to that array, then get data from a particular array stored in the multidimensional array.

For example, if we want to display data for Urus car, then, first we have to get the first array inside our multidimensional array, which can be accessed using index 0, and then inside that array, we can display all the data, like we did in associative arrays.

Accessing multidimensional array. Urus is an SUV manufactured by Lamborghini Bentayga is an SUV manufactured by Bentley

Traversing PHP Multidimensional Array

Traversing an array means to iterate it starting from the first index till the last element of the array.

Using one for loop and one foreach

In case of multidimensional array, we have to traverse the main array and then the arrays stored inside the main arrays, hence we need two loops.

Читайте также:  мос75 л с что это такое

While using the for loop to traverse a multidimensional array we must know the size/length of the array, which can be found using the count() function.

Let’s take the array defined above for the first example of traversing multidimensional array.

name : Urus type : SUV brand : Lamborghini name : Cayenne type : SUV brand : Prosche name : Bentayga type : SUV brand : Bentley

In the above multidimensional array, we have the main array as indexed array and the arrays stored as elements are associative.

Bu the main array can also be associative, let’s take an example for it.

Also, as the index in associative array is not numeric and not sequentially, hence to find the index values or keys(as data saved in associative array is in the form of key-value), we can use the function array_keys() to get an array of the keys used in the associative array.

Urus type : SUV brand : Lamborghini Cayenne type : SUV brand : Prosche Bentayga type : SUV brand : Bentley

Advantages of Multidimensional Array

Here are a few advantages of using multidimensional array in our program/script:

Источник

in_array() and multidimensional array

I use in_array() to check whether a value exists in an array like below,

or I shouldn’t be using in_array() when comes to the multidimensional array?

23 Answers 23

in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:

If you know which column to search against, you can use array_search() and array_column():

This idea is in the comments section for array_search() on the PHP manual;

This will work too.

in_array only operates on a one dimensional array, so you need to loop over each sub array and run in_array on each.

As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.

if your array like this

For Multidimensional Children: in_array(‘needle’, array_column($arr, ‘key’))

Great function, but it didnt work for me until i added the if($found) < break; >to the elseif

You could always serialize your multi-dimensional array and do a strpos :

Various docs for things I used:

Since PHP 5.6 there is a better and cleaner solution for the original answer :

With a multidimensional array like this :

We can use the splat operator :

If you have string keys like this :

You will have to use array_values in order to avoid the error Cannot unpack array with string keys :

I believe you can just use array_key_exists nowadays:

The accepted solution (at the time of writing) by jwueller

Due to PHP’s type juggling when comparing values of different type both

If this is not the desired behaviuor it can be convenient to cast numeric values to string before doing a non-strict comparison:

Источник

Образовательный портал