Given a multi-dimensional array that you don't necessarily know the structure of; how would one search for a key by name and change or add to it's contents? The value of the key could be either a string or an array and the effects should be applied either way--I had looked at array_walk_recursive, but it ignores anything that contains another array...
Does this work?
function arrayWalkFullRecursive(&$array, $callback, $userdata = NULL) {
call_user_func($callback, $value, $key, $userdata);
if(!is_array($array)) {
return false;
}
foreach($array as $key => &$value) {
arrayWalkFullRecursive($value);
}
return true;
}
arrayWalkFullRecursive($array,
create_function( // wtb PHP 5.3
'&$value, $key, $data',
'if($key == $data['key']) {
$value = $data['value'];
}'
),
array('key' => 'foo', 'value' => 'bar')
);
Array keys in PHP are ints and strings. You can't have an array array key. So yeah, array_walk_recursive() is what you want.
Related
I'm trying to find a key in an array that doesn't start with zero.
This is my not so elegant solution:
private $imagetypes = [
1 => [
'name' => 'banner_big',
'path' => 'campaigns/big/'
],
2 => [
'name' => 'banner_small',
'path' => 'campaigns/small/'
],
// ...
If i use $key = array_search('banner_big', array_column($this->imagetypes, 'name')); the result is 0
I came up with this solution but I feel like I needlessly complicated the code:
/**
* #param string $name
* #return int
*/
public function getImagetypeFromName($name)
{
$keys = array_keys($this->imagetypes);
$key = array_search($name, array_column($this->imagetypes, 'name'));
if ($key !== false && array_key_exists($key, $keys)) {
return $keys[$key];
}
return -1;
}
Is there a better solution then this.
I can't change the keys in.
Just save indexes
$key = array_search('banner_big',
array_combine(array_keys($imagetypes),
array_column($imagetypes, 'name')));
demo on eval.in
The problem is array_column will return a new array (without the existing indexes)
So in your example.
$key = array_search('banner_big', array_column($this->imagetypes, 'name'));
var_dump($key);
//$key is 0 as 0 is the key for the first element in the array returned by array_column.
You can mitigate against this by creating a new array with the existing keys.
That's because array_column() generates another array (starting at
index zero), as you may have imagined. An idea to solve this would be to
transform the array with array_map(), reducing it to key and image
name (which is what you're searching for). The keys will be the same,
and this can be achieved with a simple callback:
function($e) {
return $e['name'];
}
So, a full implementation for your case:
public function
getImagetypeFromName($name)
{
$key = array_search($name, array_map(function($e) {
return $e['name'];
}, $this->imagetypes));
return $key ?: -1;
}
I have an array which consists of arrays. So, now suppose I want to retrieve the sku and price whose
key value is 2=>5 and 3=>7 so it should return price=>13 and sku=>bc i.e. that array whose index is at 1 in the array.
Hi I would probably try the following (Same as Riziers comment)
foreach($array as $key => $item) {
if($item[2] == 5 && $item[3] == 7) {
// return price
return $item;
}
}
There is a function array_search, which does what you want but for simple values. You can define your own function that will take not $needle, but callable predicate:
function array_search_callback(callable $predicate, array $array)
{
foreach ($array as $key => $item) {
if ($predicate($item)) {
return $key;
}
}
return false;
}
Having this function your example can be done like this:
$key = array_search_callback(function ($item) {
return $item[2] === '5' && $item[3] === '7';
}, $array);
$result = $key === false ? null : $array[$key];
I could simply return an item from the search function. But to be consistent with the original search function, I am returning the index.
As array_search_callback takes callable as an argument you can provide any criteria you want without the need of modifying the function itself.
Here is working demo.
I have created an associative array
$prijs = array (
"Black & Decker Accuboormachine" => 148.85,
"Bosch Boorhamer" => 103.97,
"Makita Accuschroefmachine" => 199.20,
"Makita Klopboormachine" => 76.00,
"Metabo Klopboor" => 119.00
);
Now I have to add a value to the array and I would like to use a function for this.
function itemToevoegen($array, $key, $value){
$array[$key] = $value;
}
Then I call the function:
itemToevoegen($prijs, "Bosch GBH 18 V-LI", 412.37);
I have tried this without putting the array name in the input parameters but that does not work either.
=================== EDIT =====================
While typing this I thought I had to return the value, but that does not give me the desired result either.
function itemToevoegen($array, $key, $value){
return $array[$key] = $value;
}
Could someone help me with this and tell me what I am missing here?
Thanks in advance.
Two options:
Passing by reference
You can pass a variable by reference to a function so the function can modify the variable.
function itemToevoegen(&$array, $key, $value){
$array[$key] = $value;
}
or return array back and set new value
function itemToevoegen($array, $key, $value){
$array[$key] = $value;
return $array;
}
$prijs = itemToevoegen($prijs, "Bosch GBH 18 V-LI", 412.37);
Passing by Reference:
function itemToevoegen(&$array, $key, $value){
$array[$key] = $value;
}
Pass by reference means that you can modify the variables that are seen by the caller. To do it, prepend an ampersand to the argument name in the function definition.
By default the function arguments are passed by value, so that if the value of the argument within the function is changed, it does not get changed outside of the function.
I have tried out with the google and tried myself to get done for the below functionality. I need a function that will validate each array element whether it is scalar or not. So i wrote a simple function that will iterate each element of the array and checks for scalar or not.
But the real requirement, the array could be a multi dimentional array. So i have modified the array and called the function recursively as below, But it will not go-through all elements in the array.
function validate_scalar($params)
{
foreach ($params as $key => $arg)
{
if (is_array($arg))
{
validate_scalar($arg);
}
else
{
if (!is_scalar($arg))
{
// throwing an exception here if not scalar.
}
}
}
return true;
}
Is there any method to achieve this functionality? Please help me on this.
array_walk_recursive
You could use something like this:
<?php
$array = array(
'kalle' => 'asdf',
'anka' => array(
123,
54324,
new stdClass()
)
);
array_walk_recursive($array, function ($item, $key) {
if (!is_scalar($item)) {
echo $key . " => : Is not scalar\n";
return false;
}
echo $key . " => : Is scalar\n";
return true;
});
array_walk_recursive ignores values that are arrays
output:
kalle => : Is scalar
0 => : Is scalar
1 => : Is scalar
2 => : Is not scalar
I have a function that searches a multidimensional array for a key, and returns the path
inside the array to my desired key as a string.
Is there any way I can use this string in php to reach this place in my original array, not to get to the value but to make changes to this specific bracnch of the array?
An example:
$array = array('first_level'=>array(
'second_level'=>array(
'desired_key'=>'value')));
in this example the function will return the string:
'first_level=>second_level=>desired_key'
Is there a way to use this output, or format it differently in order to use it in the following or a similar way?
$res = find_deep_key($array,'needle');
$array[$res]['newkey'] = 'injected value';
Thanks
If the keys path is safe (e.g. not given by the user), you can use eval and do something like:
$k = 'first_level=>second_level=>desired_key';
$k = explode('=>', $k);
$keys = '[\'' . implode('\'][\'', $k) . '\']';
eval('$key = &$array' . $keys . ';');
var_dump($key);
I think you want to do a recursive search in the array for your key? Correct me if i am wrong.
Try this
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Taken from here http://in3.php.net/manual/en/function.array-search.php#91365
You need something like:
find_key_in_array($key, $array, function($foundValue){
// do stuff here with found value, e.g.
return $foundValue * 2;
});
and the implementation would be something like:
function find_key_in_array($key, $array, $callback){
// iterate over array fields recursively till you find desired field, then:
...
$array[$key] = $callback($array[$key]);
}
If you need to append some new sub-array into multidimensional complex array and you know where exactly it should be appended (you have path as a string), this might work (another approach without eval()):
function append_to_subarray_by_path($newkey, $newvalue, $path, $pathDelimiter, &$array) {
$destinationArray = &$array;
foreach (explode($pathDelimiter, $path) as $key) {
if (isset($destinationArray[$key])) {
$destinationArray = &$destinationArray[$key];
} else {
$destinationArray[$newkey] = $newvalue;
}
}
}
$res = find_deep_key($array,'needle');
append_to_subarray_by_path('newkey', 'injected value', $res, '=>', $array);
Of course, it will work only if all keys in path already exist. Otherwise it will append new sub-array into wrong place.
just write a function that takes the string and the array. The function will take the key for each array level and then returns the found object.
such as:
void object FindArray(Array[] array,String key)
{
if(key.Length == 0) return array;
var currentKey = key.Split('=>')[0];
return FindArray(array[currentKey], key.Remove(currentKey));
}