Get Key of Multidimensional Array

Get key of multidimensional array?

This is quite simple, you just need to use array_keys():

$keys = array_keys($array);

See it working

EDIT For your search task, this function should do the job:

function array_search_inner ($array, $attr, $val, $strict = FALSE) {
// Error is input array is not an array
if (!is_array($array)) return FALSE;
// Loop the array
foreach ($array as $key => $inner) {
// Error if inner item is not an array (you may want to remove this line)
if (!is_array($inner)) return FALSE;
// Skip entries where search key is not present
if (!isset($inner[$attr])) continue;
if ($strict) {
// Strict typing
if ($inner[$attr] === $val) return $key;
} else {
// Loose typing
if ($inner[$attr] == $val) return $key;
}
}
// We didn't find it
return NULL;
}

// Example usage
$key = array_search_inner($array, 'id', 9);

The fourth parameter $strict, if TRUE, will use strict type comparisons. So 9 will not work, you would have to pass '9', since the values are stored as strings. Returns the key of the first occurence of a match, NULL if the value is not found, or FALSE on error. make sure to use a strict comparison on the return value, since 0, NULL and FALSE are all possible return values and they will all evaluate to 0 if using loose integer comparisons.

How to get key of multidimensional array in foreach loop using php?

In php foreach() you can get key of current item like this

foreach ($array as $key=>$item){...}

Also use it like bottom code

foreach ($marks as $name=>$scores){
echo $name .":". $scores["chemistry"];
}

See result of code in demo

How to search by key=value in a multidimensional array in PHP

Code:

function search($array, $key, $value)
{
$results = array();

if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}

foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}

return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

Array
(
[0] => Array
(
[id] => 1
[name] => cat 1
)

[1] => Array
(
[id] => 3
[name] => cat 1
)

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

function search($array, $key, $value)
{
$results = array();
search_r($array, $key, $value, $results);
return $results;
}

function search_r($array, $key, $value, &$results)
{
if (!is_array($array)) {
return;
}

if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}

foreach ($array as $subarray) {
search_r($subarray, $key, $value, $results);
}
}

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).

How to get all the key in multi-dimensional array in php

Try this

function array_keys_multi(array $array)
{
$keys = array();

foreach ($array as $key => $value) {
$keys[] = $key;

if (is_array($value)) {
$keys = array_merge($keys, array_keys_multi($value));
}
}

return $keys;
}

Find min value in multidimensional array and return key

$dealersMin = min(array_column($dealers, 'count'));

$dealersWithMinCount = array_filter($dealers, function ($dealer) {
global $dealersMin;
return ($dealer['count'] == $dealersMin);
});

var_dump($dealersWithMinCount[array_rand($dealersWithMinCount)]['id']);

eval.in demo

Explanation

  1. First we find the lowest value of 'count' in the array and save that to $dealersMin.
  2. Then we need to get all rows in the $dealers array that have a count of $dealersMin and save that in $dealersWithMinCount.
  3. Then just pick a random element of $dealersWithMinCount with array_rand()

How to find the value of a multidimensional array by key

You can try this :

function findByKey($findKey, $array, $result = []) {
foreach ($array as $key => $value) {
if ($key === $findKey) {
$result[] = [$key => $value];
}
if (is_array($value)) {
$result = findByKey($findKey, $value, $result);
}
}
return $result;
}

The idea is to use a recursive function :

  1. you loop through your array
  2. for each key => value, you check if the key is what you want : if yes, add it to the result array, else go next
  3. if the value is an other array, you search inside this array if you have the key you want

Now use it :

$array = [
'type' => 'vacancy',
'needs' => ['root' => 'active'],
'market' => 'shopping',
'red' => 'color',
'education' => 'learning',
'fruits' => [
'red' => 'apple',
'cool' => 'cherry'
]
];

With key type :

$result = findByKey('type', $array);

var_dump($result);

Output is :

array(1) {
[0]=>
array(1) {
["type"]=>
string(7) "vacancy"
}
}

With key red :

$result = findByKey('red', $array);

var_dump($result);

Output is :

array(2) {
[0]=>
array(1) {
["red"]=>
string(5) "color"
}
[1]=>
array(1) {
["red"]=>
string(5) "apple"
}
}

Here is a link to test it : link

Getting keys of multidimensional array (of `[String: [String: String]]`)

use a Tuple will be clear try this :

let dict = ["1":["from":"aa","to":"bb"],"2":["from":"AA","to":"BB"]]

var array = [String]()
for (_ ,value) in dict{
if let v = value["from"] {
array.append(v)
}
}
print(array)

update:

let keys = dict.keys.flatMap({$0})

print(keys)

Get keys from multidimensional array recursively

This seems to work for me:

function array_keys_recursive(array $arr) {
foreach($arr as $key => $value) {
$return[] = $key;
if(is_array($value)) $return = array_merge($return, array_keys_recursive($value));
}
return $return;
}

Basically identical to yours, which also works, by the way.

How to get all values of one key from laravel multidimensional array

I got the result you want with the following test object.

$object = [
(object)['id' => 1, 'children' => []],
(object)['id' => 2, 'children' => [
(object)['id' => 4, 'children' => [
(object)['id' => 6, 'children' => []]
],
(object)['id' => 5, 'children' => []]
],
(object)['id' => 3, 'children' => []]
]
=> [
{#4565
+"id": 1,
+"children": [],
},
{#4605
+"id": 2,
+"children": [
{#4567
+"id": 4,
+"children": [
{#4563
+"id": 6,
+"children": [],
},
],
},
{#4564
+"id": 5,
+"children": [],
},
],
},
{#4551
+"id": 3,
+"children": [],
},
]

To manage it, I had to use some recursion. I am not sure it's the best but it gets the job done.

function getIds($item) {
return [$item->id, collect($item->children)->map('getIds')->all()];
}

$ids = collect($object)
->map('getIds') // call getIds function which will in turn do the same for all children
->flatten() // flatten the resulting array
->sort() // sort the resulting ids since they probably won't be in order
->values() // only interested in the values, not the keys
->all(); // transform collection to array

Code execution in Tinker console

EDIT: Found a way to further inlne this.

$ids = collect($object)
->map($closure = function($item) use (&$closure) {
return [$item->id, collect($item->children)->map($closure)->all()];
})
->flatten()
->sort()
->values()
->all();


Related Topics



Leave a reply



Submit