PHP Looping through an array with strings AND an array inside - php

This is a basic looping question but with a twist, so it's likely that i'm missing something easy - apologies in advance...
I'm trying to pull the results from an array $testoutput - which is filled with 3 arrays:
Running the following code:
foreach ($testoutput as $ID => $Array) {
echo $Array . "<BR>";
}
Returns:
ARRAY
ARRAY
ARRAY
Adding a second nested loop with the following code:
foreach ($testoutput as $ID => $Array) {
foreach ($Array as $ID => $L1item) {
echo $L1item . "<BR>";
}
}
Results in:
String1a
String1b
String1c
ARRAY
String2a
String2b
String2c
ARRAY
String3a
String3b
String3c
ARRAY
I'm fine with retuning all of the above strings, however, I can't figure out how to return the values from the 3rd-level of nested Arrays.
Is there an easy way to do this?
Many thanks in advance.

You can use array_map
$testoutput = array('x', array('y', 'z', array('1', '2', '3')));
function output($element) {
if(is_array($element)) {
array_map('output', $element); //RECURSION
return;
}
echo $element;
}
array_map('output', $testoutput);
Or if you prefer, you can use array_walk_recursive:
function output(&$value, $index) {
echo $value;
}
array_walk_recursive($testoutput, 'output');

Try this:
/**
* array nested_array_map(callback $callback, array $array)
* Warning - doesn't check for recursion,
* therefore child arrays shouldn't contain references to any of parent level arrays
*
* #param $callback, function
* #param $array, array of elements to map the function to
* #return array
*/
function nested_array_map($callback, $param) {
if (!is_array($param)) {
return call_user_func($callback, $param);
}
$result = array();
foreach ($param as $index => $value) {
$result[$index] = nested_array_map($callback, $value);
}
return $result;
}
function echo_value($value) {
echo "$value\n";
return $value;
}
$test = array(
'1st level'
,array(
'2nd level'
,array(
'3rd level'
)
,'2nd level'
)
,array(
'2nd level'
)
,'1st level'
);
$result = nested_array_map('echo_value', $test);

foreach ($testoutput as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
if(is_array($value2))
{
foreach ($value2 as $key3 => $value3) {
echo $value3;
}
}
else
{
echo $value2;
}
}
}

Related

Return doesn't work but print works

I'm trying to search in multidimensional array and get the value but return doesn't work.
function search($arr,$q){
foreach($arr as $key => $val){
if(trim($key) == $q) return $arr;
else if(is_array($val)) search($val,$q);
}
}
But echo and print work.
Where is the problem?
Not sure you've solved it already, but this is a solution that might help you on your way:
<?php
$arr = ['firstname' => 'John', 'lastname' => 'Dough', 'jobs' => ['job1' => 'writer', 'job2' => 'dad']];
$result = null; // the container for the search result
$key = 'job1'; // the key we are looking for
findKey($arr, $key, $result); // invoke the search function
/** print the result of our search - if key not found, outputs 'NULL' */
echo '<pre>';
var_dump($result); // output: string(6) "writer"
echo '<pre>';
/**
* #param array $arr the multidimensional array we are searching
* #param string $key the key we are looking for
* #param $result passed by reference - in case the key is found, this variable 'stores' the corresponding value.
*/
function findKey($arr = [], $key = '', &$result)
{
foreach ($arr as $key0 => $value0) {
if($key0 == $key) {
$result = $value0;
}
if(is_array($value0)) {
findKey($value0, $key, $result);
}
}
return false;
}

PHP search multidimensional array with more than one result?

I found a way to search my multidimensional array and output the result and it works, however it only finds the first match and stops. If I have more than one match in the array I want to be able to show them all.
My array looks like this (the first layer of keys goes from 0, 1, 2 etc):
Array
(
[0] => Array
(
[mydevice] => blahblah
[ipadd] => 10.10.10.209
[portnum] => 16040
)
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
$myoutput = searcharray($ptn2, mydevice, $newresult);
I can then echo the results using something like $newresult[$myoutput][mydevice].
However if I have more than one entry in the array with a matching data in the 'mydevice' key it doesn't return them (just the first one).
That is because return breaks the function. You could use something like this:
function searcharray($value, $key, $array) {
$result = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$result[] = $k;
}
}
return $result;
}
Now you will always get an array as result - empty if nothing was found. You can work with this like this e.g.
$mydevicekeys = searcharray($ptn2, "mydevice", $newresult);
foreach ($mydevicekeys as $mydevicekey) {
// work with $newresult[ $mydevicekey ]["mydevice"]
}
So add the results to an array :)
function searcharray($value, $key, $array) {
$res = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$res[] = $key;
}
}
return $res;
}

return row of array where key=value in multi dimentional array

array:
array(
['name'=>'kevin','value'=>'10'],
['name'=>'sam','value'=>'20']
);
how can i return value where name='sam' for example ?
and what how can i do it in even deeper array
array(
[0]=>array( 'inputs'=>
array(['name'=>'kevin','value'=>'10'],['name'=>'sam','value'=>'20']
),
[1]=>array( 'inputs'=>
array(['name'=>'kim','value'=>'10'],['name'=>'kirki','value'=>'20']
)
);
you need a recursive array_search - all answers above handle an exact amount of depth (in this case 2) only.
something like
function recursive_array_search($needle,$haystack) {
foreach ($haystack as $key=>$value) {
if ($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $value['value'];
}
}
return false;
}
recursive_array_search('sam', $start_array);
$arr = array(
array("name"=>"A","info"=>"one"),
array("name"=>"B","info"=>"two"),
array("name"=>"C","info"=>"three")
);
foreach($arr as $v){
if ($v['name']==="A"){
echo $v['info'];
}
}
In Deep Level
$arr = array(
array("input"=>array(
"name"=>"A",
"info"=>"one"
)),
array("input"=>array(
"name"=>"B",
"info"=>"Two"
))
);
foreach($arr as $subarr){ // First foreach iterate through arrays and next foreach iterate through values of each sub array
foreach($subarr as $v){
if ($v['name']==="A"){
echo $v['info'];
}
}
}
for($i=0;$i<count($array);$i++)
{
if($array['name']=="sam")
{
echo $array['value'];
}
}
and for next array you can do like this....
for($i=0;$i<count($array);$i++)
{
for($j=0;$j<count($array[$i]['inputs']);$j++)
{
if($array[$i]['inputs'][$j]['name']=="sam")
{
echo $array[$i]['inputs'][$j]['info'];
}
}
}
$new_array = array();
foreach ($old_array as $value) {
$new_array[$value['name']] = $value['value'];
}
var_dump($new_array['kevin']); // prints 10

PHP - Get the value by key in a multi-dimension array

I have a multi-dimension array like:
$fields =
Array (
[1] => Array
(
[field_special_features5_value] => Special Function 5
)
[2] => Array
(
[field_special_features6_value] => Special Function 6
)
[3] => Array
(
[field_opticalzoom_value] => Optical Zoom
)
)
I want to get the value by key, I tried the code below but not work
$tmp = array_search('field_special_features5_value' , $fields);
echo $tmp;
How can I get the value Special Function 5 of the key field_special_features5_value?
Thanks
print $fields[1]['field_special_features5_value'];
or if you don't know at which index your array is, something like this:
function GetKey($key, $search)
{
foreach ($search as $array)
{
if (array_key_exists($key, $array))
{
return $array[$key];
}
}
return false;
}
$tmp = GetKey('field_special_features5_value' , $fields);
echo $tmp;
If you know where it is located in the $fields array, try :
$value = $fields[1]['field_special_features5_value'];
If not, try :
function getSubkey($key,$inArray)
{
for ($fields as $field)
{
$keys = array_keys($field);
if (isset($keys[$key])) return $keys[$key];
}
return NULL;
}
And use it like this :
<?php
$value = getSubkey("field_special_features5_value",$fields);
?>
You need to search recursive:
function array_search_recursive(array $array, $key) {
foreach ($array as $k => $v) {
if (is_array($v)) {
if($found = array_search_recursive($v, $key)){
return $found;
}
} elseif ($k == $key) {
return $v;
} else {
return false;
}
}
}
$result = array_search_recursive($fields, 'field_special_features5_value');
Your problem is that you have a top-level index first before you can search you array. So to access that value you need to do this:
$tmp = $fields[1]['field_special_features5_value'];
You can do it with recursive function like this
<?php
function multi_array_key_exists($needle, $haystack) {
foreach ($haystack as $key=>$value) {
if ($needle===$key) {
return $key;
}
if (is_array($value)) {
if(multi_array_key_exists($needle, $value)) {
return multi_array_key_exists($needle, $value);
}
}
}
return false;
}
?>

PHP Merge Similar Objects In A Multidimensional Array

I have a multidimensional array in PHP, something that looks like:
array(array(Category => Video,
Value => 10.99),
array(Category => Video,
Value => 12.99),
array(Category => Music,
Value => 9.99)
)
and what I would like to do is combine similar categories and output everything into a table, so the output would end up being:
<tr><td>Video</td><td>23.98</td></tr>
<tr><td>Music</td><td>9.99</td></tr>
Any suggestions on how to do this?
EDIT:
I can have these in two different arrays if that would be easier.
A simple loop will do:
$array = [your array];
$result = array();
foreach ($array as $a) {
if (!isset($result[$a['Category']])) {
$result[$a['Category']] = $a['Value'];
} else {
$result[$a['Category']] += $a['Value'];
}
}
foreach ($result as $k => $v) {
echo '<tr><td>' . htmlspecialchars($k) . '</td><td>' . $v . '</td></tr>';
}
$result = array();
foreach ($array as $value) {
if (isset($result[$value['Category']])) {
$result[$value['Category']] += $value['Value'];
} else {
$result[$value['Category']] = $value['Value'];
}
}
foreach ($result as $category => $value) {
print "<tr><td>$category</td><td>$value</td></tr>";
}

Categories