Can I get all keys of an multi level associative arrays in php
Dereleased's solution will be faster I guess (as it uses internal loops), mine can also deal with array values for object_id
keys. Your tradeoff ;)
function find_all($needle, array $haystack, array &$result = null) {
// This is to initialize the result array and is only needed for
// the first call of this function
if(is_null($result)) {
$result = array();
}
foreach($haystack as $key => $value) {
// Check whether the key is the value we are looking for. If the value
// is not an array, add it to the result array.
if($key === $needle && !is_array($value)) {
$result[] = $value;
}
if(is_array($value)) {
// If the current value is an array, we perform the same
// operation with this 'subarray'.
find_all($needle, $value, $result);
}
}
// This is only needed in the first function call to retrieve the results
return $result;
}
As you can see, the result array is given to every call of the function as reference (denoted by the &
). This way, every recursive call of this function has access to the same array and can just add a find.
You can do:
$values = find_all('object_id', $array);
It gives me for your array:
Array
(
[0] => 12061
[1] => 100012061
[2] => 1000000000015
[3] => 10001
[4] => 12862
[5] => 12876
[6] => 1206102000
[7] => 1206104000
[8] => 1206101000
[9] => 1206105000
[10] => 1206106000
[11] => 10017
[12] => 100010017
[13] => 300306
[14] => 12894
[15] => 12862
[16] => 12876
[17] => 1001701000
[18] => 11990
[19] => 100011990
[20] => 12862
[21] => 12876
[22] => 10017
[23] => 12894
)
Find key of a multi-dimensional associative array by value in php
You should consider changing structure of array
. As your ID is not unique, elements with same ID stay in one array
.
$main_array = array(
1001 => array(
array('name' => 'test1'),
array('name' => 'test3'),
),
1002 => array(
array('name' => 'test2'),
)
);
So
print_r( $main_array[1001] );
would give you
Array
(
[0] => Array
(
[name] => test1
)
[1] => Array
(
[name] => test3
)
)
If this is not possible, you have to loop over the entire array to achieve this.
function arraySearchId( $id, $array ) {
$results = array();
foreach ( $array as $key => $val ) {
if ( $val['id'] === $id ) {
$results[] = $key;
}
}
return $results;
}
echo '<pre>';
print_r( arraySearchId( 1001, $main_array ) );
echo '</pre>';
Result:
Array
(
[0] => 0
[1] => 2
)
How to get an array of specific key in multidimensional array without looping
Since PHP 5.5, you can use array_column
:
$ids = array_column($users, 'id');
This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:
Since PHP 5.3, you can use array_map
with an anonymous function, like this:
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function
instead:
$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);
Iterate through every single key and value in a multi-dimensional associative array PHP
The foreach
statement has the option of iterating over just the values, as you're doing, or the keys and values. I suspect this is what you're looking for:
foreach ($arr6 as $k=>$test) {
echo $k . '<br>';
foreach ($test as $k1=>$testing1) {
echo '  ' . $k1 . '<br>';
foreach ($testing1 as $k2=>$testing2) {
echo '    ' . $testing2 . '<br>';
}
}
}
The notices you're getting are because you're trying to use echo
on an array, which is not possible.
Find all second level keys in multi-dimensional array in php
<?php
// Gets a list of all the 2nd-level keys in the array
function getL2Keys($array)
{
$result = array();
foreach($array as $sub) {
$result = array_merge($result, $sub);
}
return array_keys($result);
}
?>
edit: removed superfluous array_reverse() function
php 7 - sort multilevel associative array by keys to have it sorted on each level lexicographically
Finally, solved it.
$a = ['c'=>['d'=>1, 'a'=>2], 'b'=>['b'=>3, 'a'=>4], 'a'=>['z','x','y']];
function array_sort_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val))
$arr[$key] = array_sort_recursive($val);
}
uksort($arr, "strcmp");
return $arr;
}
$b = array_sort_recursive($a);
print_r($b);
Try it: here
PHP - Get a count of Multi-dimensional arrays within an associative array and indexed arrays
The following line of code reproduce your multidimensional array for test purpose:
$arrs=array_fill_keys(['name'],array_fill(0,49,['key1'=>1,'key2'=>2,'key3'=>2,]));
According to this:
49 - (indexed arrays within associative array 'Name')
147 - (total key-value pairs within indexed array)
3 - (key-value pairs within an indexed array)
and specifically the third line,all your counts are simplified to some simple operations that you can achieve this way:
$InArWiAsArNa=count($arrs['name']);
$KV_wi_IA=count(current($arrs['name']));
$total_KV_pairs_wi_IA=$InArWiAsArNa*$KV_wi_IA;
var_dump($InArWiAsArNa,$total_KV_pairs_wi_IA,$KV_wi_IA);
output:
int(49)
int(147)
int(3)
however if you remove the third condition, for example if the key-value pairs within an indexed array number is variable, this mean you don't need it anymore so you should loop through the array to get the two first answers:
$InArWiAsArNa=0;
$total_KV_pairs_wi_IA=0;
foreach($arrs['name'] as $key=>$val){
$InArWiAsArNa ++;
$total_KV_pairs_wi_IA+=count($val);
}
var_dump($InArWiAsArNa,$total_KV_pairs_wi_IA);
output:
int(49)
int(147)
Related Topics
Regex Ignore Url Already in HTML Tags
Problem with Adding Root Path Using PHP Domdocument
How to Post Multiple <Input Type="Checkbox" /> as Array in PHP
Permission Denied Despite Appropriate Permissions Using PHP
Why Can't I Overload Constructors in PHP
Does PHP Close the File After the File Handler Is Garbage Collected
Cannot Call Function SQLsrv_Connect()
JSON_Encode Produce JSON_Error_Utf8 from Mssql-Select
Fatal Error: Call to Undefined Function Mcrypt_Encrypt()
Printing a New Line in a CSV File Cell
How to Get List of Defined Namespaces
Using Preg_Split with Multiple Spaces
PHP SQL Select Where Like Search Item with Multiple Words
Asynchronous Processing or Message Queues in PHP (Cakephp)
PHP Object of Class Dateinterval Could Not Be Converted to String
PHP Preg_Match - Only Allow Alphanumeric Strings and - _ Characters