Iterating over a complex Associative Array in PHP - php

Is there an easy way to iterate over an associative array of this structure in PHP:
The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two).
Thoughts on doing this in a way that's nice, neat, and understandable?

Nest two foreach loops:
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}

I know it's question necromancy, but iterating over Multidimensional arrays is easy with Spl Iterators
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key=>$value) {
echo $key.' -- '.$value.'<br />';
}
See
http://php.net/manual/en/spl.iterators.php

Looks like a good place for a recursive function, esp. if you'll have more than two levels of depth.
function doSomething(&$complex_array)
{
foreach ($complex_array as $n => $v)
{
if (is_array($v))
doSomething($v);
else
do whatever you want to do with a single node
}
}

You should be able to use a nested foreach statment
from the php manual
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}

Can you just loop over all of the "part[n]" items and use isset to see if they actually exist or not?

I'm really not sure what you mean here - surely a pair of foreach loops does what you need?
foreach($array as $id => $assoc)
{
foreach($assoc as $part => $data)
{
// code
}
}
Or do you need something recursive? I'd be able to help more with example data and a context in how you want the data returned.

Consider this multi dimentional array, I hope this function will help.
$n = array('customer' => array('address' => 'Kenmore street',
'phone' => '121223'),
'consumer' => 'wellington consumer',
'employee' => array('name' => array('fname' => 'finau', 'lname' => 'kaufusi'),
'age' => 32,
'nationality' => 'Tonga')
);
iterator($n);
function iterator($arr){
foreach($arr as $key => $val){
if(is_array($val))iterator($val);
echo '<p>key: '.$key.' | value: '.$val.'</p>';
//filter the $key and $val here and do what you want
}
}

Related

Split array into key => array()

Consider the following array:
$array[23] = array(
[0] => 'FOO'
[1] => 'BAR'
[2] => 'BAZ'
);
Whenever I want to work with the inner array, I do something like this:
foreach ($array as $key => $values) {
foreach ($values as $value) {
echo $value;
}
}
The outer foreach-loop is there to split the $key and $value-pairs of $array. This works fine for arrays with many keys ([23], [24], ...)but seems redundant if you know beforehand that $array only has one key (23 in this case). In a case as such, isn't there a better way to split the key from the values? Something like
split($array into $key => $values)
foreach ($values as $value) {
echo $value;
}
I hope I made myself clear.
reset returns the first element of you array and key returns its key:
$your_inner_arr = reset($array);
$your_key = key($array);
Yea, just get rid of your first foreach and define the array you're using with the known $key of your outter array.
foreach ($array[23] as $key =>$val):
//do whatever you want in here
endforeach;
If an array has only one element, you can get it with reset:
$ar = array(23 => array('foo', 'bar'));
$firstElement = reset($ar);
A very succinct approach would be
foreach(array_shift($array) as $item) {
echo $item;
}

PHP: Get key from array?

I am sure that this is super easy and built-in function in PHP, but I have yet not seen it.
Here's what I am doing for the moment:
foreach($array as $key => $value) {
echo $key; // Would output "subkey" in the example array
print_r($value);
}
Could I do something like the following instead and thereby save myself from writing "$key => $value" in every foreach loop? (psuedocode)
foreach($array as $subarray) {
echo arrayKey($subarray); // Will output the same as "echo $key" in the former example ("subkey"
print_r($value);
}
Thanks!
The array:
Array
(
[subKey] => Array
(
[value] => myvalue
)
)
You can use key():
<?php
$array = array(
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
);
while($element = current($array)) {
echo key($array)."\n";
next($array);
}
?>
Use the array_search function.
Example from php.net
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');
foreach($foo as $key => $item) {
echo $item.' is begin with ('.$key.')';
}
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.
If you want to be in a foreach loop, then foreach($array as $key => $value) is definitely the recommended approach. Take advantage of simple syntax when a language offers it.
Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)
Try this
foreach(array_keys($array) as $nmkey)
{
echo $nmkey;
}
Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array!
PHP Manual: array_search() (similiar to .indexOf() in other languages)
public function getKey(string $value, array $target)
{
$key = array_search($value, $target);
if ($key === null) {
throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array.");
}
if ($key === false) {
throw new DomainException("The search value does not exists in the target array.");
}
return $key;
}

Retrieve array key passed on value PHP

I have the following array
$group= array(
[0] => 'apple',
[1] => 'orange',
[2] => 'gorilla'
);
I run the array group through an for each function and when the loop hits values of gorilla I want it to spit out the index of gorilla
foreach ($group as $key) {
if ($key == gorilla){
echo //<------ the index of gorilla
}
}
You can use array_search function to get the key for specified value:
$key = array_search('gorilla', $group);
foreach( $group as $index => $value) {
if ($value == "gorilla")
{
echo "The index is: $index";
}
}
array_search — Searches the array for a given value and returns the corresponding key if successful
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
foreach($group as $key => $value) {
if ($value=='gorilla') {
echo $key;
}
}
The foreach($c as $k => $v) syntax is similar to the foreach($c as $v) syntax, but it puts the corresponding keys/indices in $k (or whatever variable is placed there) for each value $v in the collection.
However, if you're just looking for the index of a single value, array_search() may be simpler. If you're looking for indices for many values, stick with the foreach.
Try this:
foreach ($group as $key => $value)
{
echo "$key points to $value";
}
foreach documentation on php.net

PHP Key name array

I have an array $data
fruit => apple,
seat => sofa,
etc. I want to loop through so that each key becomes type_key[0]['value'] so eg
type_fruit[0]['value'] => apple,
type_seat[0]['value'] => sofa,
and what I thought would do this, namely
foreach ($data as $key => $value)
{
# Create a new, renamed, key.
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
# Destroy the old key/value pair
unset($array[$key]);
}
print_r($array);
Doesn't work. How can I make it work?
Also, I want everything to be in the keys (not the values) to be lowercase: is there an easy way of doing this too? Thanks.
Do you mean you want to make the keys into separate arrays? Or did you mean to just change the keys in the same array?
$array = array();
foreach ($data as $key => $value)
{
$array['type_' . strtolower($key)] = array(array('value' => $value));
}
if you want your keys to be separate variables, then do this:
extract($array);
Now you will have $type_fruit and $type_sofa. You can find your values as $type_fruit[0]['value'], since we put an extra nested array in there.
Your requirements sound... suspect. Perhaps you meant something like the following:
$arr = array('fruit' => 'apple', 'seat' => 'sofa');
$newarr = array();
foreach ($arr as $key => $value)
{
$newkey = strtolower("type_$key");
$newarr[$newkey] = array(array('value' => $value));
}
var_dump($newarr);
First I wouldn't alter the input-array but create a new one unless you're in serious, serious trouble with your memory limit.
And then you can't simply replace the key to add a deeper nested level to an array.
$x[ 'abc[def]' ] is still only referencing a top-level element, since abc[def] is parsed as one string, but you want $x['abc']['def'].
$data = array(
'fruit' => 'apple',
'seat' => 'sofa'
);
$result = array();
foreach($data as $key=>$value) {
$target = 'type_'.$key;
// this might be superfluous, but who knows... if you want to process more than one array this might be an issue.
if ( !isset($result[$target]) || !is_array($result[$target]) ) {
$result[$target] = array();
}
$result[$target][] = array('value'=>$value);
}
var_dump($result);
for starters
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
should be
$array[str_replace("/(.+)/", type_$1[0]['value'], $key)] = $value;

In PHP how do i update values in an asssociative array and store the entire array?

Here's a code example:
$array = array();
$array['master']['slave'] = "foo";
foreach ($array as $key => $value) {
foreach ($value as $key2 => $value2) {
if (preg_match('/slave/',$key2)) {
$value[$key2] = "bar";
print "$value[$key2] => $key2 => $value2\n";
}
}
}
print_r($array);
Output:
bar => slave => foo
Array
(
[master] => Array
(
[slave] => foo
)
)
Rather i would like to have the following as the final array:
Array
(
[master] => Array
(
[slave] => bar
)
)
What wrong am i doing here?
Thank you!
Note:
Example2:
$a= array('l1'=>array('l2'=>array('l3'=>array('l4'=>array('l5'=>'foo')))));
$a['l1']['l2']['l3']['l4']['l5'] = 'bar';
foreach ($a as $i => &$values) {
foreach ( $values as $key => &$value) {
if (is_array($value)){
print_array($value,$key);
}
}
}
function print_array ($Array, $parent) {
foreach ($Array as $i1 => &$values1) {
if (is_array($values1)){
foreach ($values1 as $key1 => &$value1) {
if (is_array($value1)) {
print_array($value1,$values1);
}
else {
print " $key1 => $value1\n";
}
}
}
else {
if (preg_match('/l5/',$i1)) {
$values1 = "foobar";
print " $i1 => $values1\n";
}
}
}
}
print_r($a);
Output does not reflect 'foobar' in l5
Because foreach operates on a copy of the array. Read the documentation about foreach:
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
So you should do
foreach ($array as $key => &$value) {
foreach ($value as $key2 => $value2) {
//...
}
}
Update:
Ok, I reviewed your code again:
Your code was not working as your loops never reach the array with key l5.
The code is highly inefficient. You make assumptions about the depth of the input array. E.g. your code cannot process the input array you provide (it should work if you omit one array).
Solution:
Make use of recursion. This code works:
$a =array('l1'=>array('l2'=>array('l3'=>array('l4'=>array('l5'=>'foo')))));
function process(&$array, $needle) {
foreach($array as $k => &$v) {
if ($k == $needle) {
$v = "boooooooooo";
print "$k => $v\n";
}
if (is_array($v)) {
process($v, $needle);
}
}
}
process($a, $needle);
print_r($a);
Hope that helps.
Oh and please use other keys next time. I thought the whole time that the key was 15 (fifteen) and was wondering why my example was not working ;) (15 looks not that different from l5 at a glance).
You have a few choices, but all stem from the same problem, which originates on this line
foreach ($array as $key => $value) {
At this point in the code, $value is not a reference to 2nd dimension of arrays in your data structure. To fix this, you have a couple options.
1) Force a reference
foreach ($array as $key => &$value) {
2) Use a "fully-qualified" expression to set the desired value
$array[$key][$key2] = 'bar';
Because $value is a new variable
Why not just:
foreach ($array as $key => &$value)
{
if(isset($value['slave']))
$value['slave'] = 'bar';
};

Categories