PHP Cleaning up nested arrays with unknown structure - php

Let's assume I have an array like so:
[1=>[1=>2,2=>"something"],2=>[1,2],3=>"hello"]
The array has a "unorganized" structure with subarrays other values.
I want to run a htmlentities function on each value to make sure nothing bad is inside the values.
I've been reading up on RecursiveIteratorIterator but I cannot find an example of how to use it to apply a function to each value in a quite random nested multidimensional array. Any help is appreciated.

You could simply make use of array_walk_recursive:
array_walk_recursive($input, function (&$value) {
$value = htmlentities($value);
});
Demo: https://3v4l.org/QmRJr

Related

Is it possible to get all the nodes with a specific name from a PHP array?

I am converting to a PHP array from a Facebook API response in JSON format. The result is a multilevel array with many elements named id on every level.
I would like to retrieve all the elements with the name id and I was wondering if there is any direct way to get all those elements without having to parse each level of the array to grab the element.
Hope this question makes sense,
Any tip will be much appreciated.
Use Array Column function
$output = array_column($input, 'id');
If you do not have php 5.5 (i.e. no array_column for you), you may use this:
$ids = array_map(function($element) {return $element['id'];}, $input);

Alternative way of accessig an array within array in PHP

I'm trying to access an array within another array (basically, a two dimensional array). However, the usual way of doing this ($myarray[0][0]) doesn't work for me.
The reason is because I want to create a recursive function which, in each call, should dive deeper and deeper into a array (like, on first call it should look at $myarray[0], on second call it should look at $myarray[0][0] and so on).
Is there any alternative way of accessing an array within array?
Thanks.
Traverse the array by passing always a subarray of it to the recursive function.
function f(array &$arr)
{
// Some business logic ...
// Let's go into $arr[0]
if(is_array($arr[0]))
f($arr[0]);
}
f($myarray);

Indexing array with an array of keys Shorthand in PHP

Often I find myself with an array of keys to some other array and want to get the corresponding values. For example if I wanted to select a random subarray, the function array_rand($array) will return an array of random indices and I want to get the values. There are many examples other than this but the general problem (normally arising from functional programming style) is I have an array of keys and need the array of the corresponding values. Here is a wordy way of doing this but I was wondering if there were some shorter way to do this frequent task?
way 1:
$array_of_values = array();
foreach($array_of_indices as $index)
$array_of_values[] = $array_of_data[$index];
way 2:
function index_array($index) { return $array_of_data[$index]; }
$array_of_values = array_map("index_array", $array_of_indices);
way 3:
$array_of_values = array_intersect_key($array_of_data,
array_fill_keys($array_of_indices, ''));
I would expect that some single function to do this exists but after reading through the docs I couldn't find one. Anyone know a better way?
There is no function that will do this on its own, however there is a slightly simpler way than way 3
array_intersect_key($array_of_data, array_flip($array_of_keys));

Create associative array from numeric array and function?

I have a numeric array with codes like this: array('123', '333', '444');
I also have a function that given a code returns a name, so myFunc('123') would return 'soap'
I'd like to generate an associative array containing codes as keys and names as values. Is there any function that would allow me to do this? I know a foreach loop would do it but I wonder if there's some made function for this. Saw some methods like array_map but they don't seem to fit my needs.
array_combine($arr, array_map('myFunc', $arr))
But two functions, not one ;-) Still oneliner though

Creating an associative array from an array, based on the array - PHP

I have a unique issue that I have never heard of this being possible to do before:
So essentially I have a function that takes in a an array of arguments such as:
function someFunction(array $arguments){}
and gives me an array back as such:
array('option1', 'option2', 'options3', ...);
I then need to take that array and loop through it creating an associative array such as:
array('option1' => call_come_method('option1'), .... );
heres the kicker, you will never know how many arguments a user passes into the function, yet each one needs to created into a key=>value arrangement as seen above.
Now i did some research and I was told the $argv command in php, how ever where I am stumped is how to implement it in this case.
So if any one can give me any pointers I would be appreciative.
This is a lot easier than you think. First use array_flip to switch the array's keys and values.
$newArray = array_flip($arguments);
Then loop though it and call the method:
foreach($newArray as $key=>&$val){
$val = call_come_method($key);
}
The &, makes it a reference, so the array value is updated.
DEMO: http://codepad.org/giL1KPA3
UPDATE: You don't even need array_flip, you just need a for loop.
$newArray = array();
foreach($arguments as $val){
$newArray[$val] = call_come_method($val);
}
DEMO: http://codepad.org/AQ1gWrou
you will never know how many arguments a user passes into the function
FYI, you get to know it with func_get_args().
This way you don't need to provide your function with an $arguments parameter, but you just leave it empty.

Categories