Alternative to foreach() PHP? - php

I am still very new to PHP and from all the examples that are around they all seem to use foreach statements.
e.g.
foreach ($variable as $row)
However I don't think I should be using this all the time, for example variables or objects I have an which only has one row or instance in an array.
I know its advantageous to use them for multiple rows which could be missed if you used a for loop.
But do I really need to use it just to echo one variable thats in an array?
e.g. for example this variable $stats
array(3) { ["user_interventions"]=> int(4) ["fastest_intervention"]=> array(1) { [0]=> object(stdClass)#22 (1) { ["duration"]=> string(8) "02:10:00" } } ["slowest_intervention"]=> array(1) { [0]=> object(stdClass)#23 (1) { ["duration"]=> string(8) "02:26:00" } } }
Thanks

if you know the 'address' of the value in your array, then there's no need for a loop:
echo $arr['user_interventions'][0]['duration']; // 02:10:00
More details here.

No, you do not need to use a foreach loop every time you need to access an array value. Your example could be used in the following manner...
echo $stats['fastest_intervention']['0']->duration; // Outputs: 02:10:00
Here's your variable dump with indentation (makes it easier to read).
array(3) {
["user_interventions"]=> int(4)
["fastest_intervention"]=> array(1) {
[0]=> object(stdClass)#22 (1) {
["duration"]=> string(8) "02:10:00"
}
}
["slowest_intervention"]=> array(1) {
[0]=> object(stdClass)#23 (1) {
["duration"]=> string(8) "02:26:00"
}
}
}

You need not to use foreach here but you can't just print $array
if you indexes of array you may print something like:
print 'Key is '.$array['key'].' but index is only'.$array['index'];

You just access the variables using []. print $array['key']

Related

PHP Multidimensional Array Extract Specific Values Based Upon Key

I'm trying to create an anchor link by extracting specific array values based upon based upon the key. I've tried using a foreach loop inside of a for loop, however that doesn't seem to work.
Based upon the below multidimensional array how can I loop through each subarray to create individual anchor links, such as:
Example:
/* Array Example */
array(3) {
[0]=>
array(2) {
["#attributes"]=>
array(1) {
["id"] => string(1) "2"
}
["name"]=> string(10) "Mark"
}
[1]=>
array(2) {
["#attributes"]=>
array(1) {
["id"]=> string(1) "4"
}
["name"]=> string(8) "John"
}
[2]=>
array(2) {
["#attributes"]=>
array(1) {
["id"]=> string(1) "5"
}
["name"]=> string(10) "Suzy"
}
/* Desired Output */
Mark
John
Suzy
Let's assume the array you posted is the content of a variable called $users. You can walk through it by doing
foreach ($users as $usr)
{
$usr['#attributes']['id'];
$usr['name'];
}
This way, you can go through every node without worrying about the indexes.
You may output the link on each foreach iteration in several ways. A complete example (which allows to use HTML without escaping every special character) could be:
<?php
foreach ($users as $usr)
{ ?>
<?php echo $usr['name']; ?>
<?php } ?>
While it looks complex, with a lot of PHP opening and closing tags, it makes it easier on the markup with almost no performance penalty
You can use either ways: ($array is your array)
$names = array_column($array, 'name');
$ids = array_map(function($ele){return $ele['#attributes']['id'];}, $array);

How to loop through multidimensional array?

I'm currently getting a JSON response from a company's API and converting it into a PHP array like this:
$api_url = file_get_contents('http://example.com');
$api_details = json_decode($api_url, true);
When I run var_dump on $api_details, I am getting this:
array(2) {
["metadata"]=>
array(5) {
["iserror"]=>
string(5) "false"
["responsetime"]=>
string(5) "0.00s"
["start"]=>
int(1)
["count"]=>
int(99999)
}
["results"]=>
array(3) {
["first"]=>
int(1)
["result"]=>
array(2) {
[0]=>
array(4) {
["total_visitors"]=>
string(4) "3346"
["visitors"]=>
string(4) "3249"
["rpm"]=>
string(4) "0.07"
["revenue"]=>
string(6) "0.2381"
}
[1]=>
array(4) {
["total_visitors"]=>
string(6) "861809"
["visitors"]=>
string(6) "470581"
["rpm"]=>
string(4) "0.02"
["revenue"]=>
string(7) "13.8072"
}
}
}
}
I'm trying to do 2 things and can't figure out how to do either with a multidimensional array.
I need to check to see if metadata > iserror is false. If it is not false, I want to show an error message and not continue with the script.
If it is false, then I wants to loop through the results of results > result and echo the total_visitors, visitors, etc for each of them.
I know how to echo data from array, I guess I'm just getting confused when there's multiple levels to the array.
Anyone that can point me in the right direction would be much appreciated :)
You can iterate over arrays using foreach. You can read up on it here: http://php.net/manual/en/control-structures.foreach.php
Since you're using associative arrays, your code will look something like this:
if ($arr['metadata']['iserror']) {
// Display error here
} else {
foreach($arr['results']['result'] as $result) {
echo $result['total_visitors'];
echo $result['visitors'];
}
}
You'll have to tweak the code to fit exactly what you're doing, but this should get you over the line.
Hope that helps!

Remove element from an array

Hello I am looking for some help with removing an element from an array. My array $rooms holds events per rooms. Each room has its own array and each event has its own array within the room array. I loop through $rooms and display the room ID and within this loop I loop through the events for that room and display their contents. I would like to remove the array for the event that has been displayed so I don't have spend time comparing it when I repeat the same loop.
Below is an example of the process I am describing. I know it makes no sense to delete the element in this logic as I am using foreach, but within my application the logic of the function requires it..
$rooms
array(3)
{
[1]=> array(2)
{
["rid"]=> string(1) "1"
["events"]=> array(0)
{ }
}
[2]=> array(2)
{
["rid"]=> string(1) "2"
["events"]=> array(0)
{ }
}
[3]=> array(2)
{
["rid"]=> string(1) "3"
["events"]=> array(2)
{
[0]=> array(7)
{
["lname"]=> string(20) "xxxxxxxxxxxxxxxxxxxx"
}
[1]=> array(7)
{
["lname"]=> string(10) "yyyyyyyyyy"
}
}
}
}
loop
foreach ($rooms as $room):
echo $room['rid'];
foreach ($room['events'] as $event):
echo $event['lname'];
If you could tell me where within the foreach I should put the code and how should the code look like that would be really great. I think it should be right after echo $event['lname'], but I can't figure out how to locate the element that is displayed so I can unset it..
Thank you all for reading,
looking forward to your replies.
You can simply unset the event after echoing it, but you'll need to reference it from $rooms, so you need to use the key's at each level. Try this:
foreach($rooms as $i => $room) {
echo $room['rid'];
foreach($room['events'] as $j => $event) {
echo $event['lname'];
unset($rooms[$i]['events'][$j]);
}
}
You can see an example of it working here.

Remove keys from multidimesional array

I have an array name $json_output.
array(3) {
["ProductsSummary"]=>
array(2) {
["TotalPages"]=>
int(2)
["CurrentPage"]=>
int(1)
}
["Products"]=>
array(60) {
[0]=>
array(3) {
["LastShopUpdate"]=>
string(26) "/Date(1382716320000+0200)/"
["Score"]=>
float(0.2208696)
["ProductId"]=>
int(1306413101)
["ArticleNumber"]=>
}
[1]=>
array(3) {
["LastShopUpdate"]=>
string(26) "/Date(1382716320000+0200)/"
["Score"]=>
float(0.2208696)
["ProductId"]=>
int(1306413101)
["ArticleNumber"]=>
}
And so on. I need to unset ProductId and LastShopUpdate from each one.
What i tried:
<?php
foreach($json_output["Products"] as $bla)
unset($bla['ArticleNumber'], $bla['LastShopUpdate']);
?>
But it is not working. How could I do this?
When looping over an array using foreach, a copy is usually made. Changing something in the copy of course has no effect on the original. Try this:
foreach($json_output["Products"] as & $bla)
unset($bla['ArticleNumber'], $bla['LastShopUpdate']);
The & causes $bla to be a reference instead of a copy. Therefore it should resolve your problem.

Foreach through an array with objects and return the values and keys

array(14) {
[0]=>
object(stdClass)#2 (2) {
["set_id"]=>
int(44)
["name"]=>
string(7) "Cameras"
}
[1]=>
object(stdClass)#3 (2) {
["set_id"]=>
int(38)
["name"]=>
string(11) "Cell Phones"
}
[2]=>
object(stdClass)#4 (2) {
["set_id"]=>
int(39)
["name"]=>
string(8) "Computer"
}
The Above is my Data.
I want to return the object names ["Set_ID"] etc and the value.
I have googled and googled and tried examples from here with various failures and now I'm giving up.
I have tried to simply manually return data - ie
foreach($result as $results2)
{
foreach($results2->name as $item)
{
echo "<pre>";
print_r($item);
echo "</pre>";
}
}
I have tried all sorts of flavors of it I had kind of hoped the above would at least return data and it didn't - just errored.
In the end, I'd like to be able to both pull names and data. I don't want to have to manually find element names and code it as $result->SET_ID or whatever - I want to be able to just feed SET_ID in as a variable. I think my problem lies with it being an array of objects and I cant access that object name and all..
Im a noob, so any kind of like detailed explanation wouldn't hurt my feelings so I can learn something.
Instead of foreach($results2->name as $item) use foreach($results2 as $item). $results2->name is not an array thus causing the error.
You can read about object iteration in PHP here
foreach($result as $results2)
{
echo $results2->name.' '.$results2->set_id;
}

Categories