how to reach into PHP nested arrays? - php

I've a nested array whose print_r looks like this-
Array
(
[keyId] => Array
(
[hostname] => 192.168.1.127
[results] => Array
(
[1] => false
[2] => false
[3] => false
)
[sessionIDs] => Array
(
[0] => ed9f79e4-2640-4089-ba0e-79bec15cb25b
)
)
I would like to process(print key and value) of the "results" array. How do I do this?
I am trying to use array_keys function to first get all the keys and if key name is "results", process the array. But problem is array_keys is not reaching into the "results"

php's foreach loop is what you need.
foreach($arr['keyId']['results'] as $key => $value) {
//$key contains key and $value contains values.
}

The array you want is $array['keyID']['results']. From there you access the values with $array['keyID']['results'][1], $array['keyID']['results'][2], $array['keyID']['results'][3]
To loop through it just do this:
foreach($array['keyId']['results'] as $key => $value) {
echo $key . ' ' . $value;
}
or
for ($i = 1; $i <= 3; i++)
{
echo $i . ' ' . $array['keyID']['results'][i];
}

foreach($array['keyId']['results'] as $k => $v) {
// use $k and $v
}

One way to navigate through the array is this.
//Assuming, your main array is $array
foreach($array as $value) { //iterate over each item
if(isset($value['results']) && count($value['results'])) {
// ^ check if results is present
//Now that we know results exists, lets use foreach loop again to get the values
foreach($value['result'] as $k => $v) {
//The boolean values are now accessible with $v
}
}
}

Related

print values from multidimensional associative array in php

I have multidimensional array which contain values from database table but values are key value format so I tried to print using foreach loop but unable to get output ,so how to do this using foreach loop
after print_r() getting output like this.
echo '<pre>';
print_r($product_info);
Array
(
[product] => Array
(
[0] => Array
(
[data1] => "value1"
)
[1] => Array
(
[data2] => "value2"
)
)
[type] => 6
)
foreach ($product_info as $key => $val) {
if (is_array($val)) {
foreach ($val as $c => $d) {
echo "" . $c . " is " . $d . ".";
}
}
}
You can try to:
array_shift($product_info)
And then use foreach() on it or simply iterate over:
$product_info['product']
This will do the trick:
foreach ($product_info as $key => $val) {
//look for specific key. And do action if needed.
if($key=='product'){
$all = 0;
$all = COUNT($val); //Count lines
//loop lines
for ($x = 0; $x <= $all; $x++) {
//check if line exist
if(isset($val[$x])){
//loop through lines and echo data
foreach ($val[$x] as $c => $d) {
echo $c.' '.$d.'<br>';
}
}
}
}
if($key=='type'){
echo 'This is type: '.$val;
}
}
You should edit it for your needs but this is how you could do it!

new key/value pair not inserting in multidimensional array

I am trying to search for a value exist in multidimensional array, if exist add a new key/value pair. But i am not able to insert the new key/value pair. the multidimensional array $data is shown below.
Array ( [0] => Array ( [num] => +12000000000 [state] => eeee )
[1] => Array ( [num] => +12000000001 [state] => ) )
Another normal array $i is
Array ( [Sss] => +12000000000 [MS] => +12000000001 [KNum] => +919000000000 )
Search for num from $i exist in $data array using the below.
foreach($i as $key => $value){
$s[]= searchForId($value, $data,$key); //Edited
}
function searchForId($id, $array, $k) {
foreach ($array as $key => $val) {
if ($val['num'] === $id) {
//return $key;
echo "<br>------" . $key;
echo "<br>------" . $k;
echo "<br>------" . $id;
$array[$key]=$k;
$array[$key]['name']=$k;
return $array; //Edited
}
}
return null;
}
I tried with both the options which mentioned below but not inserting values into the $data multidimensional array. what is wrong here?
$array[$key]=$k;
$array[$key]['name']=$k;
PHP function trans parameter by value, not by reference(depreciated), if you want to modify the paremeter, return it.

How to get a value from an array

Not sure why I can't this to work. My json is:
[values] => Array
(
[0] => Array
(
[field] => id1
[value] => 985
)
[1] => Array
(
[field] => id2
[value] => 6395
)
[2] => Array
(
[field] => memo
[value] => abcde
)
I simply want the values of id2
I tried:
foreach ($json['values'] as $values) {
foreach ($json as $key=>$data) {
if ($data['field'] == 'id2') {
$result = $data['value'];
print '<br>value: '.$result;
}
}
}
Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.
there's no need for inner loop, after the first one $values already contain the exact array that you are looking for
foreach ($json['values'] as $values) // $values contain
{
if ($values['field'] == 'id2')
{
$result = $values['value'];
print '<br>value: '.$result;
}
}
foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
foreach ($values as $key=>$data) { //you're looping inside values taking the array index $key and the value inside that index $data
if ($key == 'id2') { //test if $key (index) is = to id2
print '<br>value: '.$value; // print the value inside that index
}
}
}
this is just an explanation, to what is going wrong with your code, but as #Pawel_W there is no need for the second foreach loop you can directly test
if($values['field']=='id2'){ print $values['value'];}
I think you just need to use array_search.
And here is recursive array_search ;
Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:
array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));
If your field names are always unique and you just want a single scalar:
array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });
(note that this one is not ideal since it will walk all the array even if match is found in first element)
And here's a gist with both in this and function form + output.

How to change array value from string to integer

I have the following array and I would like to change each [Entry] value from a string to an integer:
Array ( [0] => Array ( [Time] => 06:08:00 [Entry] => 250 ) [1] => Array ( [Time] => 08:08:00 [Entry] => 230 )
I am trying in this manner, which seems to change the type within the loop but the change does not seem to take effect outside the loop. I'm new at this, so I'm probably overlooking something, and most likely a simpler way to accomplish this.
foreach($data as $inner) {
foreach($inner as $key=>$val) {
if($key == 'Entry') {
$newval = intval($val);
$val = $newval;
echo(gettype($val));//integer
}
}
}
echo(gettype($data[0]['Entry'])); //string
You are not changing the Value of the element in the array.
foreach($data as &$inner) {
$inner['Entry'] = intval($inner['Entry']);
}
To modify the array elements within the loop, you have to precede $inner with &. i.e. The value will be assigned by reference.
For details see foreach
You need to re-cast it to the actual array.
foreach($data as $dkey => $inner) {
foreach($inner as $ikey => $val) {
if ($ikey == 'Entry') {
$data[$dkey][$ikey] = intval($val);
}
}
}

Getting values from associative array

I have the following main array called $m
Array
(
[0] => Array
(
[home] => Home
)
[1] => Array
(
[contact_us] => Contact Us
)
[2] => Array
(
[about_us] => About Us
)
[3] => Array
(
[feedback_form] => Feedback Form
)
[4] => Array
(
[enquiry_form] => Products
)
[5] => Array
(
[gallery] => Gallery
)
)
I have the values eg home, contact_us in a array stored $options , I need to get the values from the main array called $m using the $options array
eg. If the $options array has value home, i need to get the value Home from the main array ($m)
my code looks as follows
$c = 0;
foreach($options as $o){
echo $m[$c][$o];
++$c;
}
I somehow just can't receive the values from the main array?
I'd first transform $m to a simpler array with only one level:
$new_m = array();
foreach ($m as $item) {
foreach ($item as $key => $value) {
$new_m[$key] = $value;
}
}
Then you can use:
foreach ($options as $o) {
echo $new_m[$o];
}
Try this:
foreach($options as $o){
foreach($m as $check){
if(isset($check[$o])) echo $check[$o];
}
}
Although It would be better TO have the array filled with the only the pages and not a multidimensional array
Assuming keys in the sub arrays are unique you can
merge all sub arrays into a single array using call_user_func_array on array_merge
swap keys and values of your option array
Use array_intersect_key to retrieve an array with all the values.
Example like so:
$options = array('about_us', 'enquiry_form');
$values = array_intersect_key(
call_user_func_array('array_merge', $m), // Merge all subarrays
array_flip($options) // Make values in options keys
);
print_r($values);
which results in:
Array
(
[about_us] => About Us
[enquiry_form] => Products
)
How's this?
foreach( $options as $option )
{
foreach( $m as $m_key => $m_value )
{
if( $option == $m_key )
{
echo 'Name for ' . $options . ' is ' . $m_value;
break;
}
}
}
Try using a recursive array_walk function, for example
$a = array(
array('ooo'=>'yeah'),
array('bbb'=>'man')
);
function get_array_values($item, $key){
if(!is_numeric($key)){
echo "$item\n";
}
}
array_walk_recursive($a,'get_array_values');
Are you sure that the options array is in the same order of $m? Maybe you your
echo $m[$c][$o];
is resolving into a $m[0]['gallery'] which is obviously empty.
you can try different solutions, to me, a nice one (maybe not so efficient) should be like this:
for($c=0, $limit=count($c); $c < $limit; $c++)
if (array_search(key($m[$c]), $options))
echo current($m[$c]);
If you would like to use your approach have to flatten your array with something like this:
foreach ($m as $o)
$flattenedArray[key($o)]=current($o);
foreach ($options as $o)
echo $flattenedArray($o);
Doing this, though, eliminates duplicate voices of your original array if there are such duplicates.
$trails1 = array();
foreach ($trails as $item) {
foreach ($item as $key => $value) {
$trails1[].= $value;
}
}
echo '<pre>';print_r($trails1);
exit;

Categories