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.
Related
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";
?>
Below is dump of how my array looks like. There is inner array called officers and I would want to loop through it and check if there is officer of a specific name and if so I would want to get the index key of the outer array.
'edges' =>
array (size=59)
0 =>
array (size=3)
'source' => int 0
'target' => int 12
'officers' =>
array (size=1)
0 => string 'PARKER, Thomas, Sir' (length=19)
1 =>
array (size=3)
'source' => int 0
'target' => int 19
'officers' =>
array (size=1)
0 => string 'STEVENS, Anne' (length=13)
So if I checked for STEVENS, Anne I would want to get key 1.
Here is code I found in a different question it works with 2d arrays but not with 3d array.
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;
}
Since there can be several index keys that fit the condition, it is reasonable to implement the function as a generator:
function getOfficerIndexKey($data, $officerName) {
foreach ($data['edges'] as $key => $value) {
in_array($officerName, $value['officers']) && (yield $key);
}
}
Now you can iterate over all found values:
foreach (getOfficerIndexKey($data, 'STEVENS, Anne') as $indexKey) {
// Do something
}
As well as just get the first found one:
getOfficerIndexKey($data, 'STEVENS, Anne')->current();
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);
It may just be that I've checked out already for the weekend, but having a bit of trouble updating an associative array based on a certain value. For example, here is what I have so far:
$slideshow_vars = array(
'js_animation' => $slideshow_options['js_animation'],
'js_slide_direction' => $slideshow_options['js_slide_direction'],
'js_slideshow' => $slideshow_options['js_slideshow'],
'js_slideshow_speed' => $slideshow_options['js_slideshow_speed'],
'js_animation_duration' => $slideshow_options['js_animation_duration'],
'js_direction_nav' => $slideshow_options['js_direction_nav'],
'js_control_nav' => $slideshow_options['js_control_nav'],
'js_keyboard_nav' => $slideshow_options['js_keyboard_nav'],
'js_mousewheel' => $slideshow_options['js_mousewheel'],
'js_prev_text' => $slideshow_options['js_prev_text'],
'js_next_text' => $slideshow_options['js_next_text'],
'js_pause_play' => $slideshow_options['js_pause_play'],
'js_pause_text' => $slideshow_options['js_pause_text'],
'js_play_text' => $slideshow_options['js_play_text'],
'js_randomize' => $slideshow_options['js_randomize'],
'js_slide_start' => $slideshow_options['js_slide_start'],
'js_animation_loop' => $slideshow_options['js_animation_loop'],
'js_pause_on_action' => $slideshow_options['js_pause_on_action'],
'js_pause_on_hover' => $slideshow_options['js_pause_on_hover'],
'js_controls_container' => $slideshow_options['js_controls_container'],
'js_manual_controls' => $slideshow_options['js_manual_controls'],
'js_start_function' => $slideshow_options['js_start_function'],
'js_before_function' => $slideshow_options['js_before_function'],
'js_after_function' => $slideshow_options['js_after_function'],
'js_end_function' => $slideshow_options['js_end_function']
);
foreach ($slideshow_vars as $key => $value) {
if($value == NULL) {
$value = "false";
}
}
print_r($slideshow_vars);
In a number of the values in the array, they are outputting NULL -- well, I need to change those to a string of false (this data is being localized and then sent to a JS file which expects false). When I perform the above print_r() it hasn't actually updated anything.
That is because foreach normally passes array fields by value.
What you need to do is this:
foreach ($slideshow_vars as $key => &$value) {
if($value == NULL) {
$value = "false";
}
}
You have to update arrays like this by using the canonical path:
$slideshow_vars[$key] = 'false';
Or what cyper mentioned by using ... as $key => &$value to pass the inner loop the reference of $value instead of just its value.
Each loop, $value is set to the value. By updating the value of $value, you're just changing it in the local scope, and not setting the value inside that array. For that, you want to reference the field and update it, as such:
foreach ($slideshow_vars as $key => $value) {
if($value == NULL) {
$slideshow_vars[$key] = "false";
}
}
If all of the keys are the same and you want to save yourself a lot of code, you could try experimenting with this:
$slideshow_vars = array_merge( // Merge two arrays:
// Create an array of the same keys, but all with values of "false"
array_combine(
array_keys( $slideshow_options),
array_fill( 0, count( $slideshow_options), "false")
),
// Remove values that equal false (may need to specify a more precise callback here)
array_filter( $slideshow_options)
);
This should give you the $slideshow_vars variable you're looking for.
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;
}