Loop through nested arrays PHP - php

Im trying to loop through PHP arrays decoded from a json file. I get the results but it only gives me the first results of the arrays in the the file. How can I make it loop? This is my code:
foreach ($events as $event) {
echo $event['d']['Tree1'][0]['Tree2']['Field1'] . '<br>';
echo $event['d']['Tree1'][0]['Tree2']['Field2'] . '<br>';
echo $event['d']['Tree1'][0]['Tree2']['Field3'] . '<br>';
}

Sounds like you're trying to loop through the values of a "multidimensional array". You're starting correctly by going through your array with a loop, but then you're stuck because each element in your loop is... another array. So, to echo out the values of the child array, you want to run a second loop inside of your loop. Essentially, if your loop hits a child array, you want to loop through that array too. If you know your array is made of child arrays only, you can do this like so:
<?php
foreach ($events as $event) {
foreach($event as $ev) {
echo $ev;
}
}
If you need the keys, that adds a slight layer of complexity, but nothing you can't manage.
<?php
foreach ($events as $event) {
foreach ($event as $k=>$v) {
echo $k .': '. $v;
}
}
There are some examples in the php manual as well. You can also add in conditionals if you only need data from specific keys. Good luck!

Related

Access Element in JSON data that doesn't have a standard name

I'm using the Kraken API to get a list of available currency pairings.
Here is the endpoint: https://api.kraken.com/0/public/AssetPairs
$kraken_coins =
file_get_contents('https://api.kraken.com/0/public/AssetPairs');
$kraken_coins = json_decode($kraken_coins, true);
foreach ($kraken_coins['result'] as $coin) {
echo $coin . "<br>";
}
I'm trying to extract the first element inside of "result", however each of these elements are named differently so I'm not sure how to target it. For example, the first two currency pairings returned are "BCHEUR" and "BCHUSD".
So with the loop I have above, it just echos "Array" repeatedly... not what I'm going for.
How do I target that element so I can loop through each one? Thanks!
Since, the json structure is:
You need to use:
foreach ($array as $key => $value) {
}
In this case:
foreach ($kraken_coins['result'] as $coin => $coindata) {
echo $coin . "<br>";
}

can we skip/jump in array while displaying PHP

I have a multidimensional array returned by drupal render function in that array i want to choose some last values
for example
$array['static_name'][number]['changes_every_time']['some_name']['value_i_need'];
is there ant way we can skip the "changes_every_time" level while printing array
is there a way we can use wild character in there
like if i want to print
echo $array['static_name'][number][*]['some_name'][value_i_need];
some thing like this
Store answer "no".
But what you can do is do a foreach over the keys of $array['static_name'][number]
foreach($array['static_name'][number] as $val) {
echo $val['some_name'][value_i_need];
}
This way you don't have to care.
well, you cold iterate the array at that "level" with a foreach loop
Untested code:
foreach ($array['static_name'][number] as $key => $value) {
echo $value['some_name'][value_i_need];
}

Updating and Sorting a Multidimensional PHP Array

I have a mySQL query that dumps into an array, is sorted and then displayed, and that works perfectly.
My problem is that I want to update these values, re-sort them and display. I've been able to update the values, but it's within the same for loop and so it doesn't re-sort. So then I close the loop and re-sort but it doesn't save the updates I made in the first loop. Help is much appreciated.
foreach ($arr as $mks){
if ($mks['Column1']==$Var) {$mks['Column2'] = $mks['Column2'] + 1;
}
My sorting code
foreach ($arr as $mks){
echo $mks['Column1'] . ", " . $mks['Column2'] . "<br>";
}
How do I get this to re-save into my array properly?! I've tried googling this for most of the morning but has lead to frustration.
I think this is what you need:
foreach ($arr as $key => $mks){
if ($mks[$key] == $Var) {
$arr[$key] = $mks+1;
}
}
Now, $arr will contain the modified array, and you can use / modify it further as you need.
I don't see any "sorting code" but you can try to use references "&" instead of copy vars in your foreach(s) :
foreach($arr as & $mks){
...
}
Instead of copying your cells it will to give you a reference and every modifications done on it will be saved in the array.
Try changing your array like this instead
foreach ($arr as $key => $mks){
if ($mks['Column1']==$Var) {$arr[$key]['Column2'] = $mks['Column2'] + 1;
}

Multiple Foreach loops for one array

I have a foreach loops for an array called $feedsMerged. I have this foreach loop near the top of a document and it's setting some global variables from the array.
I'd like to recall the foreach loop, or run it again on that array and this time build elements from the variables I set above.
Top of the document.
foreach ($feedsMerged as $posts) {
$post_id = $post['post_id'];
etc etc
}
Then bottom of page
foreach ($feedsMerged as $posts) {
echo '<div class="' . $post_id . '">stuff</div>';
}
Is this possible to do? The reason for using two foreach loops on the same array is I'd like to keep this all organized and I'll have content in between each foreach that can't be in this foreach
No problem at all. You can access an array as many times as you like using any supported method in a script.

PHP : how to use foreach loop inside an echo statement?

i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.

Categories