PHP Multidimensional Array Get Values

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

how to get all values from an multi dimensional array

Something like this should do it:

$result = [];
array_walk_recursive($input, function($value, $key) use(&$result) {
if ($key === 'id') {
$result[] = $value;
}
});

PHP - Get multidimensional array value based on the value of another parameter

Try this:

$index = array_search($user->user_email, array_column($array, 'email'));
if ($index !== false) $name = $array[$index]['name'];

This relies on the fact that the runtime array created by array_column preserves, I believe, the order in which the items were extracted. Ergo, an index read from this array can be used to reference the original array.

Get column of data from third level of a multidimensional array

There are several ways to extract a column of data from the third level of a multidimensional array. Different techniques will have trade-offs. The following demonstrations will all generate the same output. (Demo Link)

Eliminate top level of structure with spread operator before isolating columns


  • array_column(array_merge(...$data), 'Date')
  • Pros:
    • it is the most concise option
    • it does not iterate any data unnecessarily
    • array_column() doesn't need to check if the column key exists to avoid warnings
    • it perfectly fits into a codebase using functional stylings -- IOW, the return value is immediately accessible and no extra variable needs to be declared
  • Cons:
    • if you, your development team, or your future development team are not familiar with variadics, then this one-liner is not very intuitive. On the other hand, raising awareness of how to flattening an array will be good for your team; maybe just write a note in your code and link to a SO page or the php docs for quick reference.

Check leaf-node keys recursively (not recommended)


  • $result = [];
    array_walk_recursive(
    $data,
    function($v, $k) use (&$result) {
    if ($k === 'Date') {
    $result[] = $v;
    }
    }
    );
  • Pros:
    • because array_walk_recursive() traverses leaf-nodes and 'Data' is always "scalar", all Date elements will be found
    • if the level structure changes, the code will still work because array_walk_recursive is level-ignorant
  • Cons:
    • array_walk_recursive() traverses leaf-nodes, it will visit ALL scalar elements in the structure which means there will be some useless processing
    • not very concise and involves an anonymous function which requires $result to be declared as a modifiable-by-reference variable
    • if the data type of Date changes to something iterable, then it ceases to be a leaf-node

Loop and push elements columns using the spreading operator


  • $result = [];
    foreach ($data as $group) {
    array_push($result, ...array_column($group, 'Date'));
    }
    var_export($result);
  • Pros:
    • it is not too verbose and does not involve an anonymous function (so no modifiable-by-reference variable)
    • it does not iterate any data unnecessarily
  • Cons:
    • it doesn't lend itself to a functional programming style because a $result variable must be declared
    • if you, your development team, or your future development team are not familiar with variadics; maybe just write a note in your code and link to a SO page or the php docs for quick reference.

Classic nested foreach loops


  • $result = [];
    foreach ($data as $group) {
    foreach ($group as $row) {
    if (array_key_exists('Date', $row)) {
    $result[] = $row['Date'];
    }
    }
    }
  • Pros:
    • probably the most intuitive/semantic for developers of any experience level
    • it does not iterate any data unnecessarily
    • it has minimal functional overhead* so it will potentially perform the best on huge data sets (be sure to benchmark if this is a reasonable concern)
  • Cons:
    • it is completely procedural style and requires a $result variable to be declared
    • it is relatively verbose
  • *The condition with array_key_exists() will not be necessary if the input data is guaranteed to contain the Date element on all levels. If they are not guaranteed to exist, then the condition serves to prevent warnings.

extract set of values from multidimensional array using an index

Following logic might help you on your way: cycle through the whitelist ($array1) and if id is present in $array2 store the resulting record in $result array.

<?php
$array1 = ["1","2","12","43","52"];

$array2 = [
["id"=>"12","name"=>"Robert","surname"=>"Plant"],
["id"=>"43","name"=>"Jimmy","surname"=>"Page"],
["id"=>"8","name"=>"Mary","surname"=>"Stilton"]
];

$result = []; // result store
foreach($array1 as $whitelisted) {
foreach($array2 as $record) {
if($record['id'] == $whitelisted) $result[] = $record;
}
}

working demo

How to find value inside multidimensional array without looping?

Use https://www.php.net/manual/en/function.array-column.php for this.

As this is a builtin function it should perform better than doing your own loop.

Example:

$accountDescriptions = array_column($accounts,'desc','account');

Will result in:

Array
(
[ACR016] => Salary
[ACR017] => Bonuses
)

Alternatively you can use:

Example:

$accountDescriptions = array_column($accounts,null,'account');

Then you will get all data keyed with account instead of numeric index.

PHP Multidimensional Array - Get value of element in last index?

You can do something like this.
First accessing until the desired level, then pick the last array of each, check if it is an array and then print the value "Date".

Assuming that the multi-array in the example is stored in a variable named $array:

foreach($array["something"]["Something1"] as $value) {
foreach($value as $value1){
if(is_array(end($value1))) {
echo(end($value1)["Date"]);
}
}
}

In case your multi-array deviates from the example you have indicated maybe you should add some extra validation.


Edited to show an example saving the values into a variable instead of printing them.

// First declare an array to store all values
$var = array();

// Then extract all values and save them into $var
foreach($array["something"]["Something1"] as $value) {
foreach($value as $value1){
if(is_array(end($value1))) {
array_push($var, end($value1)["Date"]); // Add the value at the end of the $var array
}
}
}

// Finally you have all values stored into the $var array

// If you know the number of values, you can access them one by one
$var[num]; // Where 'num' is the position of the value stored into the array (0,1,2...)

// Or you can loop it

foreach ($var as $date) {
// do whatever with each $date value
}

PHP: Use array to get value in another, multidimensional array

You might want to create some kind of helper function, where you iterate over parts of your path while keeping track of your temporary result:

function deep_array_get(array $path, array $subject) {

$result = $subject;
foreach ($path as $p) {
$result = $result[$p];
}

return $result;

}

Example:

$p = ["a", "b", "c"];
$s = [1, 2, "a" => [3, 4, "b" => ["c" => 5]]];
var_dump(deep_array_get($p, $s));

// Result: int(5)

In your exact usecase it would be used something like this:

$path = ['neighborhood', 'street', 'house'];
$subject = get_option($options_id);

$result = deep_array_get($path, $subject);

How to get values of a multidimensional array with a string

With reset() you get the first element.

echo reset($array[1]);  //text1


Related Topics



Leave a reply



Submit