My PHP foreach code is not working properly - php

I found that in PHP I can use two types of foreach.
Here is the code:
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
foreach ($p2 as $item => $desc)
{
echo "$item -> $desc <br />";
}
echo "<br />";
while (list($item, $desc) = each($p2))
{
echo "$item -> $desc <br />";
}
The second while loop does not iterate over the items. Why?

After the first foreach() is done, the internal "current position" indicator on the $p2 is at the END of the array. You need to reset() that pointers so the while() loop starts at the beginning again. e.g.
foreach($p2 as $item => $desc) {
....
}
reset($p2); // <--you need this
while(list(...) = ...) {
...
}
foreach() does this reset for you implicitly each time you foreach() the array, so if your code had been the other way around (while loop then the foreach), you wouldn't have this problem.

Related

How to parse an object containing multidimensional array

I have an object $userStatus which is fetching the values in the following format via an API call.
I am unable to allocate the values via loop.
foreach($usersStatus as $user => $element) {
print "[".$user."] => ". $element ."<br />";
}
The following script in php allows me to print the first set of values until the key ["total_time"] => String96) "6m 34s" but then I get a following warning
Warning: Array to string conversion in C:\XAMPP\htdocs\Check-status.php on line 119
[units] => Array
Is there a way, I can traverse the whole object including the two arrays [0][1] using a loop and assign any value to any variable.
I know vardump will print the whole thing, but I want to traverse the whole object via loop or nested loops.
["role"]=>string(7) "learner"
["enrolled_on"]=>string(20) "05/01/2021, 17:44:53"
["enrolled_on_timestamp"]=>string(10) "1609868693"
["completion_status"]=>string(9) "Completed"
["completion_percentage"]=>string(3) "100"
["completed_on"]=>string(20) "06/01/2021, 16:58:23"
["completed_on_timestamp"]=>string(10) "1609952303"
["expired_on"]=>string(0) ""
["expired_on_timestamp"]=>NULL
["total_time"]=>string(6) "6m 34s"
["units"]=>array(2) {
[0]=>array(8) {
["id"]=>string(4) "2047"
["name"]=>string(26) "MyCourse1 2019"
["type"]=>string(19) "SCORM | xAPI | cmi5"
["completion_status"]=>string(9) "Completed"
["completed_on"]=>string(20) "06/01/2021, 16:58:23"
["completed_on_timestamp"]=>string(10) "1609952303"
["score"]=>NULL
["total_time"]=>string(6) "3m 56s"
}
[1]=>array(8) {
["id"]=>string(4) "2059"
["name"]=>string(34) "Assessment - MyCourse1"
["type"]=>string(4) "Test"
["completion_status"]=>string(9) "Completed"
["completed_on"]=>string(20) "06/01/2021, 15:06:56"
["completed_on_timestamp"]=>string(10) "1609945616"
["score"]=>string(5) "91.67"
["total_time"]=>string(6) "2m 38s"
}
}
Thank you for your help!
Check if $element is array to avoid this
foreach($usersStatus as $user => $element) {
// check if the value is not array
if (!is_array($element)) {
print "[".$user."] => ". $element ."<br />";
} else {
// value is array do with it whatever you want
// like another foreach for example
foreach($element as $key => $value) {
// do whatever
}
}
}
array_walk_recursive will satisfy your example. It will apply a user function to every member of an array while recursively doing so if the type is an array.
array_walk_recursive($arr, function ($val, $key) {
echo "[" . $key . "] => " . $val . "<br />";
});

How to access the attributes within this JSON string in PHP

So I have this array that saves a json string.
Array
(
[0] => "2jDQoU9D2wu04wqkg0ImUI":{"date":"2016-08-02 14:08:49","type":"story","story_id":"2jDQoU9D2wu04wqkg0ImUI","series_id":"1RAv0uDbcIieYgYqywqYmk"}
)
I want to be able to access just the value "2jDQoU9D2wu04wqkg0ImUI" at the start of the json string and then also be able to do something like $value[0]['type'] to get the type from this json string object. I'm pretty new to PHP and struggling to get this working. I've tried JSON encoding/decoding and can't seem to get anything to work.
What's the proper way to go about this? Thanks in advance.
I hope this code will solve your problem.
$array[0] = '"2jDQoU9D2wu04wqkg0ImUI":{"date":"2016-08-02 14:08:49","type":"story","story_id":"2jDQoU9D2wu04wqkg0ImUI","series_id":"1RAv0uDbcIieYgYqywqYmk"}';
//print_r($arr);
$JsonString = '{' . $array[0] . '}';
$json = json_decode($JsonString);
foreach($json as $key => $value){
echo "Key : $key <br />";
echo "Type : ". $value->type."<br />";
echo "date : ". $value->date."<br />";
echo "story_id : ". $value->story_id."<br />";
echo "series_id : ". $value->series_id."<br />";
}
so you have array $jsonArray and you want to access just the key of it
if its single dimension array :
echo key($jsonArray); //prints 2jDQoU9D2wu04wqkg0ImUI
Otherwise if its multidimensional you can loop through it and do whatever you want with each key
foreach($jsonArray as $key => $value) {
echo $key; //prints 2jDQoU9D2wu04wqkg0ImUI
}
Try this:
$arrayOfObjects = [];
foreach($array as $key => $value) arrayOfObjects[] = json_decode($value);
Now you can loop through this new $arrayOfObjects
foreach($arrayOfObjects as $key => $object){
echo $object->date . '<br>';
echo $object->type . '<br>';
echo $object->story_id . '<br>';
echo $object->series_id . '<br> ==== >br> ';
}

php foreach loop with continue if value has already been echoed

I have a foreach loop and I need to add a continue if the value has already been echoed. I can't find the right syntax. The loop:
foreach ($results as $result) {
echo $result->date . "<br />";
}
But I need to add in a continue so that if the value has already been echoed, and it comes up again in the loop it gets skipped. I can't quite get the if/continue statement quite right.
Thoughts, suggestions, ideas?
As mentioned by #JonathanKuhn in the comments - here is how you would run that loop:
$already_echoed = array();
foreach ($results as $result) {
if (!in_array($result->date, $already_echoed)) { //check if current date is in the already_echoed array
echo $result->date . "<br />";
}
$already_echoed[] = $result->date; //store all dates in an array to check against.
}
$echoedArray = array();
foreach ($results as $result) {
if (isset($echoedArray[$result->date])) {
continue;
}
echo $result->date . "<br />";
$echoedArray[$result->date] = true;
}
$alreadyOutput = array();
foreach ($results as $result) {
if(in_array($result->date, $alreadyOutput)){
continue;
}
$alreadyOutput[] = $result->date;
echo $result->date . "<br />";
}

How to access info stored in session array?

Given the following code:
session_start();
$cart = $_SESSION['cart'];
print_r($_SESSION['cart']);
I can then see what I want to access:
Array ( [153c740f526f2fa8aac9e1ddfdce2716] => Array ( [deal_id] => 38 [variation_id] => [variation] => [quantity] => 6 [data] =>......
There is still more but that is the basics...
What I want to be able to do is get and set the quantity:
So I've tried:
$cart = $_SESSION['cart'];
for ($i = 0 ; $i < count($cart) ; $i ++)
{
echo "The session variable you want" . $_SESSION['cart'][$i]['deal_id'];
echo "<br>";
}
But there is no output, what am I doing wrong?
foreach ($_SESSION['cart'] as $k => $data) {
echo "The session variable you want" . $data['deal_id'];
$_SESSION['cart'][$k]['deal_id'] = 'new id';
}
According to the data you just printed, within 'cart', the array is associative, and not numerical.
To iterate through an associative array, use the foreach with $someArray as $key => $val expression
The cart is not indexed by sequencial indexes, you can not loop it that way, you need to use a foreach loop:
foreach($_SESSION['cart'] as $index => $value)
echo "Var = " . $value['deal_id'];
If you want to set the value, loop the values by reference
foreach($_SESSION['cart'] as $index => &$value)
{
echo "Var = " . $value['deal_id'];
$value['deal_id'] = 'newValue';
}
You will simplify things by using foreach loop
foreach ($_SESSION['cart'] as $k => $data) {
echo "The session variable you want" . $data['deal_id'];
echo "<br>";
$_SESSION['cart'][$k] = "new Value";
}
Use the foreach loop to iterate through the $_SESSION array:
foreach($cart as $k=> $value){
echo "The session variable you want" . $data['deal_id']. "<br>";
$_SESSION['cart'][$k] = "newValueGoesHere"; //setting the new value
}
you use the foreach statement
foreach($cart as $key=>$value){
echo "The session variable you want" . $value['deal_id'];
echo "<br>";
}

php built in counter for what iteration foreach loop is currently in

I have an associative array. Two dimensions which I am iterating through like this
foreach ( $order_information as $sector_index => $sector_value ){
echo 'sector : ' . current($order_information) ;
echo '<br>';
foreach ( $sector_value as $line_index => $line_value ){
}
}
The current() is an attempt to get the iteration the loop is in. It seems like this should give me that. However, elsewhere on that page there is the suggestions that you just do like
$index = 0
foreach ( $array as $key => $val ) {
echo $index;
$index++;
}
I wonder if I am using current incorrectly, as echo 'sector : ' . current($order_information); just prints sector : Array
Is $index++ bad syntax? Is there a better way to do this?
Answer
As far as I know there is no build in numeric counter in a foreach loop in PHP.
So you need your own counter variable. Your example code looks quite good to do that.
$index = 0;
foreach($array as $key => $val) {
$index++;
}
By the way, $index++; is fine.
Example
Here is an example illustrating which variable stores which value.
$array = array(
"first" => 100,
"secnd" => 200,
"third" => 300,
);
$index = 0;
foreach($array as $key => $val) {
echo "index: " . $index . ", ";
echo "key: " . $key . ", ";
echo "value: " . $val . "\n";
$index++;
}
The output will be that.
index: 0, key: first, value: 100
index: 1, key: secnd, value: 200
index: 2, key: third, value: 300
Current-Function
I think you misunderstood current($array). It gives you the value pointed by an internal array pointer, which can be moved using next($array), prev($array) and end($array).
Take a look at the manual to make thinks clear.

Categories