print values from multidimensional associative array in php - 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!

Related

PHP format an array of arrays into a flat array

I have an generated array into this format and want to generated a second array to fit into a file that expects the specific format
This is the array i have :
(int) 0 => array(
[Service] => Array
(
[id] => 6948229
[document] => Array
(
[number] => 0003928425
)
)
This is the array i want to build from the previous array (will have many indexes)
verified[id]
verified[number]
So far i build this script:
foreach($data as $key=>$value )
{
echo '<br>key '.$key;
foreach($value as $k=>$v)
{
$Verified[$key]['id'] = $v["id"];
$Verified[$key]['number'] = $v['document']['number'];
But just get undefined index error message.
Which indexes i must use to get the flatten array ?
From what I can make from your question, you can do something like this to get the desired output,
$Verified = []; //use array() for versions below 5.5
foreach($data as $key=>$value )
{
echo '<br>key '.$key;
foreach($value as $k=>$v)
{
if(is_array($v)){
$Verified[$key]['number'] = $v['document']['number'];
}
$Verified[$key]['id'] = $v['id'];
Please pass your array to this function
function arrayconvert($arr) {
if (is_array($arr)) {
foreach($arr as $k => $v) {
if (is_array($v)) {
arrayconvert($v);
} else {
$newarr[$k] = $v;
}
}
}
return $newarr;
}
There is no need of second foreach and you are getting undefined index because you are using $v['id'] insted of $val['id'] in that line $Verified[$key]['id'] = $v["id"];
<?php
$data = array('Service' => array('id' => 6948229,'document' => array ('number' => '0003928425' )));
$verified = array();
foreach($data as $key => $val)
{
$verified[$key]['id'] = $val['id'];
$verified[$key]['number'] = $val['document']['number'];
}
echo "<pre>"; print_r($verified);
?>
output
Array
(
[Service] => Array
(
[id] => 6948229
[number] => 0003928425
)
)

How to Print associative array in foreach

I have an associative array in php, how can i print it with php foreach loop
Array( [0] => Array ( [fb_user_id] => 100000058716604 [accept_status] => 1 ) [1] => Array ( [fb_user_id] => 100004069844270 [accept_status] => 1 ) )
Tried this but no success, i want to print the fb_user_id
foreach($resulttotal[fb_user_id] as $value)
{
echo $value;
}
Please help me, Thanks
You doing incorrectly, It will be like:
foreach($resulttotal as $value)
{
echo $value['fb_user_id'];
}
It would make more sense to use a regular for loop.
for($i = 0; $i < count($resulttotal); $i++) {
$row = & $resulttotal[$i];
echo $row['fb_user_id'];
}
But this could be a foreach too.
foreach($resulttoal as $key) {
echo $key['fb_user_id']
}

how to reach into PHP nested arrays?

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
}
}
}

How to access first level keys of a 2d array with a foreach loop? [duplicate]

This question already has answers here:
How to loop through an associative array and get the key?
(12 answers)
Closed 4 months ago.
How do I access the first level key of a two-dimensional array using a foreach loop?
I have a $places array like this:
[Philadelphia] => Array
(
[0] => Array
(
[place_name] => XYX
[place_id] => 103200
[place_status] => 0
)
[1] => Array
(
[place_name] => YYYY
[place_id] => 232323
[place_status] => 0
)
This is my view code that loops over the array:
<?php foreach($places as $site): ?>
<h5><?=key($site)?></h5>
<?php foreach($site as $place): ?>
<h6><?=$place['place_name']?></h6>
<?php endforeach?>
<?php endforeach ?>
Where I call key($site), I want to get Philadelphia, but I am just getting place_name from each row.
You can access your array keys like so:
foreach ($array as $key => $value)
As Pekka stated above
foreach ($array as $key => $value)
Also you might want to try a recursive function
displayRecursiveResults($site);
function displayRecursiveResults($arrayObject) {
foreach($arrayObject as $key=>$data) {
if(is_array($data)) {
displayRecursiveResults($data);
} elseif(is_object($data)) {
displayRecursiveResults($data);
} else {
echo "Key: ".$key." Data: ".$data."<br />";
}
}
}
You can also use array_keys() . Newbie friendly:
$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk);
for($i=0; $i < $arraySize; $i++) {
echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}
foreach($shipmentarr as $index=>$val){
$additionalService = array();
foreach($additionalService[$index] as $key => $value) {
array_push($additionalService,$value);
}
}

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