Answer : There are multiple solutions nested array_column()
, foreach
, array_walk_recursive()
I have an array which is multidimensional. I have to pull a key as column but it is nested. like object accessing how to achieve this with minimum line of code or optimized.
$array = [['price' => ['cost' => 200, 'tax' => 10, 'total' => 210],'otherKey' => 'etc'],['price' => ['cost' => 500, 'tax' => 50, 'total' => 550],'otherKey' => 'etc'],['price' => ['cost' => 600, 'tax' => 60, 'total' => 660],'otherKey' => 'etc'],];
array_column()
method:$result = array_column(array_column($array, 'price'), 'total');printf($result);
array: [
0 => 210
1 => 550
2 => 660
]
foreach
method:$result = [];foreach ($array as $value) {$result[] = $value['price']['total'];}printf($result);
array_walk_recursive()
method:$totals = [];array_walk_recursive($array,function($leafNode, $key) use(&$totals) {if ($key === 'total') {$totals[] = $leafNode;}});printf($totals);
Answers 1 : of How to get column from a multidimensional with nested key foreach is better way to do that even you can do a benchmark for performance you can have idea.
Answers 2 : of How to get column from a multidimensional with nested key The simple foreach should do the job, you could also write a function which takes a string as input, splits it and retrieves the values from the array.
Answers 3 : of How to get column from a multidimensional with nested key It will only visit ”leafnodes” so it spares you from needing to check if an element is an array or not.
Multidimensional data can be used to describe a lot of different things. For example, you can have a multidimensional column representing your customers and their relationship with your company. You can also have a multidimensional column that describes the amount of time you spent with each customer and the number of times you interacted with them.
Multidimensional data is a type of data that can be represented using more than two dimensions. This makes it possible to represent data in a way that is not just linear but also non-linear.
String and number data types are used in most applications today, such as in web development, mobile app development, etc.
In the past, a database was a collection of information stored in different physical locations. Nowadays, it is more like an idea or a representation of data. Data can be stored in databases and retrieved through queries and functions.
Quick Links
Legal Stuff
Social Media