PHP - Accessing Multidimensional Array Values

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;
}
});

How to access multidimensional array with php

You can use foreach and inside foreach add a condition if it's an array

Solution:

$data = array(
array('id' => '207'),
array('id' => '1474'),
'date' => 'Fri Dec 08 2017 00:00:00 GMT+0700 (WIB)',
'content' => 'test'
);

foreach($data as $key => $val){
if(is_array($val)){
//We can use foreach instead of printin it out directly
//if this array will have more value
//If not just use $val['id']
foreach($val as $k => $v){
echo $k . ' = ' . $v . '<br />';
}
}else{
echo $key . ' = ' . $val . '<br />';
}
}

OUTPUT

id = 207
id = 1474
date = Fri Dec 08 2017 00:00:00 GMT+0700 (WIB)
content = test

Dynamically accessing multidimensional array value

Try this

function flatCall($data_arr, $data_arr_call){
$current = $data_arr;
foreach($data_arr_call as $key){
$current = $current[$key];
}

return $current;
}

OP's Explanation:

The $current variable gets iteratively built up, like so:

flatCall($data_arr, ['a','ab','abc']);

1st iteration: $current = $data_arr['a'];
2nd iteration: $current = $data_arr['a']['ab'];
3rd iteration: $current = $data_arr['a']['ab']['abc'];

You could also do if ( isset($current) ) ... in each iteration to provide an error-check.

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.

Access a Multidimensional Array Value in Laravel Blade

So the answer was because some of the data was missing, and Laravel complains about this...

So this is the answer to solve the problem, using the optional() helper method.

{{ optional($customer->BillAddr)->Line1 }}

Is there a way to dynamically access multidimensional PHP array?

In your case you will need something like this:

<?php


function getArray($i, $j, $k, $array) {
if (isset($array[$i]['children'][$j]['children'][$k]['country']['city']))
{
return $array[$i]['children'][$j]['children'][$k]['country']['city'];
}
}

$array[0]['children'][0]['children'][0]['country']['city'] = "some value";
$array[0]['children'][0]['children'][1]['country']['city'] = "another";
$array[0]['children'][1]['children'][1]['country']['city'] = "another one";
.
.
.
etc


echo getArray(0,0,0, $array) . "\n"; // output -> "some value"
echo getArray(0,0,1, $array) . "\n"; // output -> "another"
echo getArray(0,1,1, $array) . "\n"; // output -> "another one"

Another thing to keep in mind is that you have called the function passing only one parameter. And your multidimensional array needs at least three.

getArrayValue('1,0,2')

You have to take into account that you have called the function passing only one parameter. Even if there were commas. But it's actually a string.

getArrayValue(1,0,2) //not getArrayValue('1,0,2') == string 1,0,2

If you want to pass two values, you would have to put at least one if to control what you want the function to execute in that case. Something like:

  function getArray($i, $j, $k, $array) {
if($k==null){
if(isset($array[$i]['children'][$j]['country']['city'])){
return $array[$i]['children'][$j]['country']['city']; //
}
} else {
if(isset($array[%i]['children'][$j]['children'][$k]['country']['city'])){
return $array[$i]['children'][$j]['children'][$k]['country']['city'];
}
}
}

getArray(0,0,null, $array)
getArray(0,0,1, $array)

For the last question you can get by using the eval() function. But I think it's not a very good idea. At least not recommended. Example:

echo ' someString ' . eval( 'echo $var = 15;' );

You can see the documentation: https://www.php.net/manual/es/function.eval.php

edit:
I forgot to mention that you can also use default arguments. Like here.

<?php

$array[0]['children'][0]['children'][0]['country']['city'] = "some value";
$array[0]['children'][0]['children'][1]['country']['city'] = "another";
$array[0]['children'][1]['children'][1]['country']['city'] = "another one";

function getArray($array,$i, $j, $k = null) {
if($k==null){
echo 'getArray called without $k argument';
echo "\n";
}
else{
echo 'getArray called with $k argument';
echo "\n";
}

}

getArray($array,0,0); //here you call the function with only 3 arguments, instead of 4
getArray($array,0,0,1);

In that case $k is optional. If you omit it, the default value will be null. Also you have to take into account that A function may define default values for arguments using syntax similar to assigning a variable. The default is used only when the parameter is not specified; in particular, note that passing null does not assign the default value.

<?php
function makecoffee($type = "cappuccino"){
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");

The above example will output:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

You can read more about that here: https://www.php.net/manual/en/functions.arguments.php

How to access and manipulate multi-dimensional array by key names / path?

Assuming $path is already an array via explode (or add to the function), then you can use references. You need to add in some error checking in case of invalid $path etc. (think isset):

$key = 'b.x.z';
$path = explode('.', $key);

Getter

function get($path, $array) {
//$path = explode('.', $path); //if needed
$temp =& $array;

foreach($path as $key) {
$temp =& $temp[$key];
}
return $temp;
}

$value = get($path, $arr); //returns NULL if the path doesn't exist

Setter / Creator

This combination will set a value in an existing array or create the array if you pass one that has not yet been defined. Make sure to define $array to be passed by reference &$array:

function set($path, &$array=array(), $value=null) {
//$path = explode('.', $path); //if needed
$temp =& $array;

foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}

set($path, $arr);
//or
set($path, $arr, 'some value');

Unsetter

This will unset the final key in the path:

function unsetter($path, &$array) {
//$path = explode('.', $path); //if needed
$temp =& $array;

foreach($path as $key) {
if(!is_array($temp[$key])) {
unset($temp[$key]);
} else {
$temp =& $temp[$key];
}
}
}
unsetter($path, $arr);

*The original answer had some limited functions that I will leave in case they are of use to someone:

Setter

Make sure to define $array to be passed by reference &$array:

function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;

foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}

set($arr, $path, 'some value');

Or if you want to return the updated array (because I'm bored):

function set($array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;

foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;

return $array;
}

$arr = set($arr, $path, 'some value');

Creator

If you wan't to create the array and optionally set the value:

function create($path, $value=null) {
//$path = explode('.', $path); //if needed
foreach(array_reverse($path) as $key) {
$value = array($key => $value);
}
return $value;
}

$arr = create($path);
//or
$arr = create($path, 'some value');

For Fun

Constructs and evaluates something like $array['b']['x']['z'] given a string b.x.z:

function get($array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$result = \$array{$path};");

return $result;
}

Sets something like $array['b']['x']['z'] = 'some value';:

function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$array{$path} = $value;");
}

Unsets something like $array['b']['x']['z']:

function unsetter(&$array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("unset(\$array{$path});");
}

Access value of wordpress multidimensional array

Notice that the array contains objects. You should be able to access name and slug for each object like this:

foreach ($specs as $object) {
echo $object->name . ' ' . $object->slug;
}


Related Topics



Leave a reply



Submit