I've been stuck on this for like 2 days, and I know it's much more simpler than I think it is..
I have a foreach loop that goes like this.
foreach($appointments as $appointment){
$list = $appointment['techs']
}
The $appointment['techs']; comes out of the database like this.
a:2:{i:0;s:1:"1";i:1;s:2:"12";}
My question is, how to I get loop through appointments and then show the users that are assigned to each appointment...
The desired output should look like this,
{ resource : 1, event : 1},{ resource : 12, event : 1}
I've literally tried everything! Any help would be greatly appreciated.
$array = [];
$string = 'a:2:{i:0;s:1:"1";i:1;s:2:"12";}';
$arr = (unserialize($string));
foreach ($arr as $item){
array_push($array, json_encode(['resource'=> $item, 'event'=>1]));
}
$i = 0;
$numItems = count($array);
foreach ($array as $item) {
if (++$i === $numItems) {
echo $item;
}
else{
echo $item.',';
}
}
// Output: {"resource":"1","event":1},{"resource":"12","event":1}
The PHP command unserialize it's what you are looking for.
foreach($appointments as $appointment){
$list = unserialize($appointment['techs']);
}
Related
My Script :
<?php
$values='Product1,54,3,888888l,Product2,54,3,888888l,';
$exp_string=explode(",",$values);
$f=0;
foreach($exp_string as $exp_strings)
{
echo "".$f." - ".$exp_string[$f]." ";
if ($f%3==0)
{
print "<br><hr><br>";
}
$f++;
}
?>
With this code i want show data inside loop, the idea it´s show all information in groups the elements in each group it´s 4 elements and must show as this :
Results :
Group 1 :
Product1,54€,3,green
Group 2:
Product2,56€,12,red
The problem it´s i don´t know why, don´t show as i want, and for example show separate some elements and not in group, thank´s , regards
It looks like you are trying to combine elements of a for loop and a foreach loop.
Here is an example of each, pulled from the php manual:
For Loop
for($index = 0, $index < size($array), $index++ {
//Run Code
//retrieve elements from $array with $array[$index]
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
It's hard for me to understand what your input looks like. If you post an example of $exp_strings, I could be of better assistance. But from the sound of your question, if $exp_strings is multidimensional if you need to loop through groups of items, you could try nesting one loop inside another loop like so:
$groups_of_data = array(array(...), array(...), array(...));
for($i = 0, $i < size($groups_of_data), $i++) {
$group = $i;
for($j = 0, $j < size($groups_of_data[$i]), $j++) {
// print out data related to group $i
}
}
This is really all guesswork on my part though as I can't see what your input string/array is. Can you post that? Maybe I can be of more help.
here is code i worked out. it was kind of since i did't know what object $exp_string is. if it's a string you should tokenize it, but i think it's array from database. there was another problem, with your code where it tries to output $exp_string[$f] it should be $exp_strings what changes in the loop.
my code
$exp_string=array("Product"=>54,"price"=>3,"color"=>"green");
$f=0;
foreach($exp_string as $key => $exp_strings)
{
if($f%3==0)
{
print "<br><hr><br>";
echo "Product ".$exp_strings."<br> ";
}
else if($f%3==1)
{
echo "Price ".$exp_strings."<br> ";
}
else if($f%3==2)
{
echo "Color ".$exp_strings."<br> ";
}
$f++;
}
hope it's any help, maybe not what you wanted.
$values='Product1,1,2,3,Product2,1,2,3,Product3,1,2,3';
$products = (function($values) {
$exp_string = explode(',', $values);
$products = [];
for ($i=0; $i+3<count($exp_string); $i+=4) {
$product = [
'title' => $exp_string[$i],
'price' => $exp_string[$i+1],
'color' => $exp_string[$i+2],
'num' => $exp_string[$i+3],
];
array_push($products, $product);
}
return $products;
})($values);
/* var_dump($products); */
foreach($products as $product) {
echo "{$product['title']},{$product['price']},{$product['color']},{$product['num']}<br>";
}
Hello I am trying to update an value in an multi dimensional array which was not working can any one tell me what is the issue in the below code.
<?php
$array_m= array();
array_push($array_m,array('md5'=>'a','count'=>1));
array_push($array_m,array('md5'=>'b','count'=>1));
foreach ($array_m as $key=>$val)
{
if($val['md5']=='a') {
$val['count'] =5;
break;
}
}
print_r($array_m);
foreach ($array_m as $key=>$val)
This just loops through the values, you can't update them. You need to use a reference, so you can update the array.
foreach ($array_m as $key=>&$val)
Note the &, that will make it a reference.
You have the $key so you can reference the array using that:
if($val['md5']=='a') {
$array_m[$key]['count'] = 5;
break;
}
You should Chnage your Code like following,
<?php
$array_m= array();
$array_m[] = array('md5'=>'a','count'=>1);
$array_m[] = array('md5'=>'b','count'=>1);
foreach ($array_m as $key=>$val)
{
if($val['md5']=='a') {
$val['count'] =5;
break;
}
}
print_r($array_m);
You can set the value of 5 like this:
$array_m[$key]['count'] = 5;
i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}
How to calculate how many items in a foreach?
I want to count total rows.
foreach ($Contents as $item) {
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
If you just want to find out the number of elements in an array, use count. Now, to answer your question...
How to calculate how many items in a foreach?
$i = 0;
foreach ($Contents as $item) {
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
$i++;
}
If you only need the index inside the loop, you could use
foreach($Contents as $index=>$item) {
// $index goes from 0 up to count($Contents) - 1
// $item iterates over the elements
}
You don't need to do it in the foreach.
Just use count($Contents).
count($Contents);
or
sizeof($Contents);
foreach ($Contents as $index=>$item) {
$item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
There's a few different ways you can tackle this one.
You can set a counter before the foreach() and then just iterate through which is the easiest approach.
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
Try:
$counter = 0;
foreach ($Contents as $item) {
something
your code ...
$counter++;
}
$total_count=$counter-1;
$Contents = array(
array('number'=>1),
array('number'=>2),
array('number'=>4),
array('number'=>4),
array('number'=>4),
array('number'=>5)
);
$counts = array();
foreach ($Contents as $item) {
if (!isset($counts[$item['number']])) {
$counts[$item['number']] = 0;
}
$counts[$item['number']]++;
}
echo $counts[4]; // output 3
foreach ($array as $value)
{
if(!isset($counter))
{
$counter = 0;
}
$counter++;
}
//Sorry if the code isn't shown correctly. :P
//I like this version more, because the counter variable is IN the foreach, and not above.
You can do sizeof($Contents) or count($Contents)
also this
$count = 0;
foreach($Contents as $items) {
$count++;
$items[number];
}
Imagine a counter with an initial value of 0.
For every loop, increment the counter value by 1 using $counter = 0;
The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}
Try that.
$index = 0;
foreach( $array ?? [] as $index=> $item ) {
$index++;
$data[] = array(
'id' =>$index
);
}
Using a regular for loop, it's possible to comapred the current index with the last to tell if I'm in the last iteration of the loop. Is there a similar thing when using foreach? I mean something like this.
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = islast(); //boolean true/false
}
If not, is there at least a way to know the current index of the current iteration like $iteration = 5, so I can manually compare it to the length of the $array?
The counter method is probably the easiest.
$i = count($array);
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = !(--$i); //boolean true/false
}
You can use a combination of SPL’s ArrayIterator and CachingIterator class to have a hasNext method:
$iter = new CachingIterator(new ArrayIterator($arr));
foreach ($iter as $value) {
$last_iteration = !$iter->hasNext();
}
Here are a few methods for this;
$items = ["Bhir", "Ekky", null, "Uych", "foo"=>"bar"];
$values = array_values($items);
// Bhir, Ekky, Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = isset($values[$i + 1]);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = array_key_exists($i + 1, $values);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$i = count($values);
foreach ($items as $item) {
print("$item");
$next = !!(--$i);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$items = new \CachingIterator(new \ArrayIterator($items));
foreach ($items as $item) {
print("$item");
$next = $items->hasNext();
if ($next) {
print(", ");
}
}
No, you need to have a counter and know the amount of items in the list. You can use end() to get the last item in an array and see if it matches the current value in your foreach.
If you know that the values of the array will always be unique, you can compare the current $item to end($array) to know if you're at the last item yet. Otherwise, no, you need a counter.
You can get the key and the value in foreach() like this:
foreach($array as $key=>$value) { ... }
Alternatively, you could do a count() of the array so you know how many items there are and have an incrementing counter so that you know when you've reached the last item.
end($array);
$lastKey = key($array);
foreach($array as $key => $value) {
if ($key === $lastKey) {
// do something endish
}
}
The valid() method says if the ArrayIterator object has more elements.
See:
$arr = array("Banana","Abacaxi","Abacate","Morango");
$iter = new ArrayIterator($arr);
while($iter->valid()){
echo $iter->key()." - ".$iter->current()."<br/>";
$iter->next();
}