I've tried to display this information tons of times, i've looked all over stackoverflow and just can't find an answer, this isn't a duplicate question, none of the solutions on here work. I've a json array which is stored as a string in a database, when it's taken from the database it's put into an array using json_decode and looks like this
Array
(
[0] => Array
(
[0] => Array
(
)
[1] => Array
(
[CanViewAdminCP] => Array
(
[Type] => System
[Description] => Grants user access to view specific page
[Colour] => blue
)
)
)
)
However, when i try to loop through this, it just returns nothing, I've tried looping using keys, i've tried foreach loops, nothing is returning the values, I'm looking to get the Array key so "CanViewAdminCP" and then the values inside that key such as "Type" and "Description".
Please can anybody help? thankyou.
Use a recursive function to search for the target key CanViewAdminCP recursively, as follows:
function find_value_by_key($haystack, $target_key)
{
$return = false;
foreach ($haystack as $key => $value)
{
if ($key === $target_key) {
return $value;
}
if (is_array($value)) {
$return = find_value_by_key($value, $target_key);
}
}
return $return;
}
Example:
print_r(find_value_by_key($data, 'CanViewAdminCP'));
Array
(
[Type] => System
[Description] => Grants user access to view specific page
[Colour] => blue
)
Visit this link to test it.
You have a 4 level multidimensional array (an array containing an array containing an array containing an array), so you will need four nested loops if you want to iterate over all keys/values.
This will output "System" directly:
<?php echo $myArray[0][1]['CanViewAdminCP']['Type']; ?>
[0] fetches the first entry of the top level array
[1] fetches the second entry of that array
['CanViewAdminCP'] fetches that keyed value of the third level array
['Type'] then fetches that keyed value of the fourth level array
Try this nested loop to understand how nested arrays work:
foreach($myArray as $k1=>$v1){
echo "Key level 1: ".$k1."\n";
foreach($v1 as $k2=>$v2){
echo "Key level 2: ".$k2."\n";
foreach($v2 as $k3=>$v3){
echo "Key level 3: ".$k3."\n";
}
}
}
Please consider following code which will not continue after finding the first occurrence of the key, unlike in Tommassos answer.
<?php
$yourArray =
array(
array(
array(),
array(
'CanViewAdminCP' => array(
'Type' => 'System',
'Description' => 'Grants user access to view specific page',
'Colour' => 'blue'
)
),
array(),
array(),
array()
)
);
$total_cycles = 0;
$count = 0;
$found = 0;
function searchKeyInMultiArray($array, $key) {
global $count, $found, $total_cycles;
$total_cycles++;
$count++;
if( isset($array[$key]) ) {
$found = $count;
return $array[$key];
} else {
foreach($array as $elem) {
if(is_array($elem))
$return = searchKeyInMultiArray($elem, $key);
if(!is_null($return)) break;
}
}
$count--;
return $return;
}
$myDesiredArray = searchKeyInMultiArray($yourArray, 'CanViewAdminCP');
print_r($myDesiredArray);
echo "<br>found in depth ".$found." and traversed ".$total_cycles." arrays";
?>
Related
I have heterogenous nested arrays (each contains a mix of scalars and arrays, which also may contain scalars and arrays, and so on recursively). The goal is to extract all arrays with the maximum depth. Note this does not mean extracting arrays at the "bottom" of any given sub-array (local maximums), but the greatest depth over all sub-arrays.
For example:
$testArray= array(
'test1' => 'SingleValue1',
'test2' => 'SingleValue2',
'test3' => array(0,1,2),
'test4' => array(array(3,4,array(5,6,7)), array(8,9,array(10,11,12)),13,14),
'test5' => array(15,16,17, array(18,19,20)),
);
In this example, the greatest depth any array occurs at is 3, and there are two arrays at that depth:
array(5,6,7)
array(10,11,12)
The code should find these two. (The [18,19,20] sub-array is not included, for though it's at the greatest depth in its branch, it's at a lesser depth overall.)
I'm not sure where to start. I've tried many things: using foreach in recursive functions, etc., but the end result was always nothing, all elements or the last iterated element. How can this problem be approached? Complete solutions aren't needed, just hints on where to start.
Extended solution with RecursiveIteratorIterator class:
$testArray= array(
'test1' => 'SingleValue1',
'test2' => 'SingleValue2',
'test3' => array(0,1,2),
'test4' => array(array(3,4,array(5,6,7)), array(8,9,array(10,11,12)),13,14),
'test5' => array(15,16,17, array(18,19,20)),
);
$it = new \RecursiveArrayIterator($testArray);
$it = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
$max_depth = 0;
$items = $deepmost = [];
foreach ($it as $item) {
$depth = $it->getDepth(); // current subiterator depth
if ($depth > $max_depth) { // determining max depth
$max_depth = $depth;
$items = [];
}
if (is_array($item)) {
$items[$depth][] = $item;
}
}
if ($items) {
$max_key = max(array_keys($items)); // get max key pointing to the max depth
$deepmost = $items[$max_key];
unset($items);
}
print_r($deepmost);
The output:
Array
(
[0] => Array
(
[0] => 5
[1] => 6
[2] => 7
)
[1] => Array
(
[0] => 10
[1] => 11
[2] => 12
)
)
You may wrap this approach into a named function and use it for getting the deepmost arrays.
Enjoy! )
Roman's solution seems to work, but I struggle to read that type of method. Here's my version of finding the deepest subarrays.
See my inline comments for explanation of each step. Basically, it checks each array for subarrays, then iterates/recurses when possible, and storea subarrays using the level counter as a key.
My custom function will return an array of arrays.
Code: (Multidimensional Array Demo) (Flat Array Demo) (Empty Array Demo)
function deepestArrays(array $array, int $level = 0, array &$lowest = []): array
{
$subarrays = array_filter($array, 'is_array');
if ($subarrays) { // a deeper level exists
foreach ($subarrays as $subarray) {
deepestArrays($subarray, $level + 1, $lowest); // recurse each subarray
}
} else { // deepest level in branch
$lowestLevel = key($lowest) ?? $level; // if lowest array is empty, key will be null, fallback to $level value
if ($lowestLevel === $level) {
$lowest[$level][] = $array; // push the array into the results
} elseif ($lowestLevel < $level) {
$lowest = [$level => [$array]]; // overwrite with new lowest array
}
}
return current($lowest); // return the deepest array
}
var_export(
deepestArrays($testArray)
);
I have a script where I want to get name of a column in array().
From API, I can get an array() with multiple values and I would like to get the name of a specific column.
I don't have columns' names, how do I get a list of them and fetch one by one?
Here, I want to get "573" only.
Array ( [success] => 1 [errors] => Array ( ) [data] => Array ( [Messages] => Array ( [573] => PHP is fun ) ) )
Thanks.
You just have to do a recursive iterator that will use itself to recurse or return a value based on the key match:
<?php
$arr = array(
'success' => 1,
'errors' => array(),
'data' => array(
'Messages' => array(
573 => 'PHP is fun'
)
)
);
function recurseIt($array,$find = false)
{
# Loop through array
foreach($array as $key => $value) {
# If the key is the same as the value
if($key == $find)
# Send back the value
return $value;
# If the value is an array
if(is_array($value)) {
# Use same array to recurse the array
$val = recurseIt($value,$find);
# If there is a value to return
if(!empty($val))
# Send it back
return $val;
}
}
}
# Note, if the key matches, could also be an array
echo recurseIt($arr,573);
Gives you:
PHP is fun
EDIT:
Presumably you have the value if you don't know the key, so this will return the key based on the search value:
function recurseIt($array,$find = false)
{
foreach($array as $key => $value) {
# If the key is the same as the value
if(!is_array($value) && ($value == $find))
# Send back the key name
return $key;
if(is_array($value)) {
$val = recurseIt($value,$find);
if(!empty($val))
return $val;
}
}
}
echo recurseIt($arr,'PHP is fun');
Gives you:
573
Now, if you don't know what the key name is and don't know the associated value would be, then the function doesn't know how to search. read_my_mind() is not yet in the PHP library so at that point you are pretty much out of luck.
I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);
I'm sure this has been asked before, but I can't seem to find the answer.
To that end, I have an array that looks like this:
Array
(
[0] => Array
(
[status] => active
[sid] => 1
)
[1] => Array
(
[status] => expired
[sid] => 2
)
)
What I'd like to be able to do is type $arrayName["active"] and it return the SID code. I will be using this like a dictionary object of sorts. It's like I need to reindex the array so that it is the key/value pair that I need. I was just wondering if there was an easier way to do it.
You should convert your nested arrays into a single associative array. Something like this should take your example and turn it into an associative array:
$assoc_array = array();
foreach( $example_array as $values ) {
$assoc_array[$values["status"]] = $values["sid"];
}
You can then access the sid for a given status by using $assoc_array["expired"] (returns 2)
After seeing the others' solutions, I realize this might be bit of an overkill, but I'm still just gonna throw it out there:
$foo = array(
array('status' => 'active', 'sid' => 1),
array('status' => 'expired', 'sid' => 2),
);
// Get all the 'status' elements of each subarray
$keys = array_map(function($element) {
return $element['status'];
}, $foo);
// Get all the 'sid' elements of each subarray
$values = array_map(function($element) {
return $element['sid'];
}, $foo);
// Combine them into a single array, with keys from one and values from another
$bar = array_combine($keys, $values);
print_r($bar);
Which prints:
Array
(
[active] => 1
[expired] => 2
)
Manual pages:
array_map()
array_keys()
array_values()
array_combine()
Anonymous functions
You can use this function:
function findActive($my_array){
foreach($my_array as $array){
foreach($array as $val){
if($val['status']==='active'){
return $val['sid'];
}
}
}
return false;
}
access it via a loop or directly.
if($arrayName[0]['status'] == "active") {
echo $arrayName[0]['sid'];
}
If you want to check all the SIDs
foreach($arrayName as $item) {
if($item['status'] == "active") {
echo $item['sid'];
}
}
A more direct approach is just putting the loop in a function and return an array of all active session IDs
$sidArr = array();
foreach($yourArr as $val) {
if("active" == $val["status"]) {
array_push($sidArr, $val["sid"]);
}
}
reindex would be the best
$arrayName = array()
foreach ($data_array as $data)
$arrayName[$data['status']]=$data['sid'];
Or use a function
function get_sid($status)
{
global $data_array;
foreach ($data_array as $data) {
if ($data['status']==$status)
return $data['sid'];
}
return false;
}
I am using below code to find an array inside parent array but it is not working that is retuning empty even though the specified key exits in the parent array
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $cards_parent[$key];
break;
}
}
Do you know any array function that will search parent array for specified key and if found it will create an array starting from that key?
you want array_key_exists()
takes in a needle (string), then haystack (array) and returns true or false.
in one of the comments, there is a recursive solution that looks like it might be more like what you want. http://us2.php.net/manual/en/function.array-key-exists.php#94601
here you can use recursion:
function Recursor($arr)
{
if(is_array($arr))
{
foreach($arr as $k=>$v)
{
if($k == 'Cards')
{
$_GLOBAL['cards'][] = $card;
} else {
Recursor($arr[$k]);
}
}
}
}
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$_GLOBAL['cards'] = array();
Recursor($cards_parent);
Could you please put a print_r($feedData) up? I ran the below code
<?php
$feedData = array('BetradarLivescoreData' => array('Sport' => array('Category' => array('Tournament' => array('Match' => array('Cards' => array('hellow','jwalk')))))));
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $card;
break;
}
}
print_r($cards);
And it returned a populated array:
Array ( [0] => Array ( [0] => hellow [1] => jwalk ) )
So your code is correct, it may be that your array $feedData is not.