Problem: I have a foreach loop in a while loop. for each row selected from the database the foreach loop has to done. but when I echo $row it seems like it immedieatly puts out all the rows and then afterwards goes trough the foreach just once. I've read through the manuals but it did not help me unfortunately.
Code:
$conn = oci_connect('login', 'pass', '127.0.0.1/xe');
$stid = oci_parse($conn, 'select TOKEN, SECRET from TOKENS');
oci_execute($stid);
$time=20:00
while(($row = oci_fetch_row($stid)) != false) {
$fitbit->setOAuthDetails($row[0], $row[1]);
//retreive steps. (with date and time)
$steps = $fitbit->getTimeSeries('steps', '2015-06-01', '2015-07-01');
$n=0;
foreach ($steps as $value){
$sqlArray[$n]['dateTime']=$value->dateTime;
$sqlArray[$n]['time'] = $time;
$sqlArray[$n]['steps'] = $value->value;
$n++;
}
}
It's probably me overlooking something but I hope my question can be answered.
Updated code:
$time="12:00";
$n=0;
$x=0;
while(($row = oci_fetch_row($stid)) != false) {
$sqlArray[$n]['token'] = $row[0];
$sqlArray[$n]['secret'] = $row[1];
echo 'hoi';
$fitbit->setOAuthDetails($sqlArray[$n]['token'], $sqlArray[$n]['secret']);
//retreive steps. (with date and time)
$steps = $fitbit->getTimeSeries('steps', '2015-06-01', '2015-07-01');
foreach ($steps as $value){
$sqlArray[$n][$x]['dateTime']=$value->dateTime;
$sqlArray[$n][$x]['time'] = $time;
$sqlArray[$n][$x]['steps'] = $value->value;
$x++;
}
//retreive calories and add to sqlArray where date matches. (used for testing now, when acces to intraday api the outcommented code below will be used.
$calories = $fitbit->getTimeSeries('caloriesOut', '2015-06-01', '2015-07-01');
$x=0;
foreach ($calories as $value){
$checkdate=$value->dateTime;
if ($sqlArray[$n][$x]['dateTime'] == $checkdate){
$sqlArray[$n][$x]['calories'] = $value->value;
}
$x++;
}
$n++;
};
Now my output is as follows:
Array
(
[0] => Array
(
[token] => token
[secret] => secret
[0] => Array
(
[dateTime] => 2015-06-01
[time] => 12:00
[steps] => 8046
[calories] => 2785
)
Which iteraties nicely over the tokens from the database. Though, After the first iteration the calories are dropped:
[1] => Array
(
[token] => token
[secret] => secret
[31] => Array
(
[dateTime] => 2015-06-01
[time] => 12:00
[steps] => 8046
)
I guess I'm doing something wrong again... I think it has to do with the $x variable, but I am not sure.
Yep it's me! I placed $x=0; in the while loop now and it works good!
Thanks for the help!
Please do like below:-
$conn = oci_connect('login', 'pass', '127.0.0.1/xe');
$stid = oci_parse($conn, 'select TOKEN, SECRET from TOKENS');
oci_execute($stid);
$time='20:00';
$new_array = array(); // create a new array
$i = 0;
while(($row = oci_fetch_row($stid)) != false) {
$new_array[$i][] = $row[0]; // assign values to that new array
$new_array[$i][] = $row[1]; // assign values to that new array
$i++;
}
$sqlArray = array(); // create another new array
$n=0;
foreach($new_array as $array){
$fitbit->setOAuthDetails($array[0], $array[1]); // iterate on first array values
//retreive steps. (with date and time)
$steps = $fitbit->getTimeSeries('steps', '2015-06-01', '2015-07-01');
$sqlArray[$n]['dateTime']=$value->dateTime; // assign value to new array
$sqlArray[$n]['time'] = $time; // assign value to new array
$sqlArray[$n]['steps'] = $value->value; // assign value to new array
$n++;
}
Now what ever you want to do do on $sqlArray which is multidimensional array and you can check it's structure by echo "<pre/>";print_r($sqlArray);
Try this:
$n=0; // Initiate $n
while(($row = oci_fetch_row($stid)) != false) {
$fitbit->setOAuthDetails($row[0], $row[1]);
$steps = $fitbit->getTimeSeries('steps', '2015-06-01', '2015-07-01');
// Dont initiate $n here
foreach ($steps as $value){
$sqlArray[$n]['dateTime']=$value->dateTime;
$sqlArray[$n]['time'] = $time;
$sqlArray[$n]['steps'] = $value->value;
// Dont increment $n here
}
$n++; // Increment $n 'outside' your foreach
}
Related
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:
one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.
I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the
second JSON --> for ex: {"blog_heading":"def"}
Now, i have to replace the value of second json to first json. example output for above scenario like I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:
output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.
So i am trying as below,
$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{
$log->debug($key . ': ' . $value);
if (array_key_exists($key, $id5->data)) {
$log->debug($key . 'element is in the array');
$log->debug($value . 'element is in the array');
//array_push($id5, "apple", "raspberry");
$id3 = array($key => $value);
$id3[$key] = $value;
$log->debug($id3);
}else{
$log->debug($key . 'element is not in the array');
}
}
$id7 = json_encode($id2);
$log->debug($id7);
id5 data is : $id5
DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
(
[meta] => stdClass Object
(
[table] => story
[type] => item
)
[data] => stdClass Object
(
[id] => 7
[active] => 1
[blogId] => abc
[blog_heading] => xyz
)
)
==================
Log of $id :
stdClass Object
(
[active] => 1
[blog_heading] => def
[id] => 7
)
Please suggest me how can i achieve this... Anything i am doing wrong here
Please try that:
$j1 = '{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$j2 = '{"blog_heading":"def"}';
$result = json_encode(
array_merge(
json_decode($j1, true),
json_decode($j2, true)
)
);
<?php
$json1='{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$json2='{"blog_heading":"def"}';
$json1=json_decode($json1);
$json2=json_decode($json2);
foreach ($json1 as $key => $value) {
if($json2->$key){
$json1->$key=$json2->$key;
}
}
$json1=json_encode($json1);
$json2=json_encode($json2);
If you have only one element in array,Do like this
$a = json_decode('{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}',true);
$b = json_decode('{"blog_heading":"def"}',true);
$a['blog_heading'] = $b['blog_heading'];
print_r($a);
If you have multiple element like this :
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"blog_heading":"def"},{"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
$c[$i]['blog_heading'] = $d[$i]['blog_heading'];
$return[] = $c[$i];
}
print_r($return);
If you want to replace value by specific id
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":7,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
if($d[$i]['id'] == $c[$i]['id']) {
$c[$i]['blog_heading'] = $d[$i]['blog_heading'];
}
$return[] = $c[$i];
}
print_r($return);
Checking dynamic key value pair :
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":6,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
$result = array_intersect_key($c[$i], $d[$i]);
foreach ($result as $key => $value) {
$c[$i][$key] = $d[$i][$key];
}
$return[] = $c[$i];
}
print_r($return);
Check demo here
I am new to multidimensional array in php, I read this SO answer and I tried to create my bidimensional array but how do I output it?
$nPost = array("orange, table");
$count_values = array("fruit, forniture");
$final_array = array(array($count_values), array($nPost));
Output would have to be:
Fruits: orange, Forniture: table
Tried
print_r($final_array);
But i got
Array ( [0] => Array ( [0] => Array ( [0] => fruit, forniture ) ) [1] => Array ( [0] => Array ( [0] => orange, table ) ) )
0 fruit, forniture
UPDATE
Real life full code is (explanation in code comments):
<?php
$stack = array();
$userID = array();
$nPost = array();
$blogusers = get_users( 'orderby=nicename&role=author' );
foreach ( $blogusers as $user ) {
// get the language list for each user, and push to array
$descTokens = explode(',', $user->user_description);
$stack = array_merge($stack, $descTokens);
// get the ID for each user, and push to the array
// get the number of posts for each user ID and push to array
$the_user_id = $user->ID;
$numPosts = count_user_posts( $the_user_id );
array_push($userID, $the_user_id);
array_push($nPost, $numPosts);
}
// get the count for each language by counting the duplicate strings
$count_values = array();
foreach ($stack as $a) {
#$count_values[$a]++;
}
$total_duplicates = 0;
foreach ($count_values as $a) {
if($count_values[$a]<=1){
unset($count_values[$a]);
} else{
$total_duplicates += $count_values[$a];
}
}
for($i = 0; $i < count($count_values); $i++){
$final_array[$count_values[$i]] = $nPost[$i];
}
foreach($final_array as $label => $item){
echo "$label: $item, ";
}
?>
// This gives me a correct result but not the n. posts
<ul>
<?php
foreach ($count_values as $key=>$count) {
echo '<li>'.$key.' '.$count.'</li>';
}
?>
</ul>
What we're trying to achieve is:
1 French with 2 posts
3 English with 5 posts
<?php
class User {
public $id;
public $numPosts;
public $languages = array();
public function __construct($id, $numPosts, $lang = array()){
$this->id = $id;
$this->numPosts = $numPosts;
$this->languages = $lang;
}
}
$users = array();
$john = new User(1, 4, array("English", "French"));
$fred = new User(2, 3, array("English"));
$dave = new User(3, 7, array("German", "French", "Spanish"));
$users[] = $john;
$users[] = $fred;
$users[] = $dave;
$langPostCount = array();
$langUserCount = array();
foreach($users as $user){
foreach($user->languages as $lang){
$langUserCount[$lang] += 1; // this is what you already have from $count_values
//$langPostCount[$lang] += $user->numPosts; // can be done here but we'll do another loop
}
}
/*
* the following can be done in the above loop, but you already have that functionality in your code
* just need to do another loop through your languages, tallying the number of posts in that language
* keep in mind this is not entirely accurate as your users have multiple languages. they might have
* one post in english and 4 in french. A better way to do this would be to select the number of posts
* in each language directly from the posts database.
*/
foreach($langUserCount as $lang => $userCount){
foreach($users as $user){
if(in_array($lang, $user->languages)){
$langPostCount[$lang] += $user->numPosts;
}
}
}
echo "<ul>";
foreach($langUserCount as $lang => $userCount){
echo "<li>$userCount $lang with " . $langPostCount[$lang] . " posts.</li>";
}
echo "</ul>";
?>
OUTPUT
2 English with 7 posts.
2 French with 11 posts.
1 German with 7 posts.
1 Spanish with 7 posts.
As you can see, not entirely accurate. You're better off getting post count by querying your posts dataset than by working from the bottom up.
Try This
Adds a new tally to the foreach loop at the top, and changes the ul loop at the end.
$postsPerLanguage = array(); // add this
foreach ( $blogusers as $user ) {
$descTokens = explode(',', $user->user_description);
...
$numPosts = count_user_posts( $the_user_id );
...
// add this loop
foreach($descTokens as $lang){
$postsPerLanguage[$lang] += $numPosts;
}
}
...
<ul>
<?php
foreach ($count_values as $key=>$count) {
echo '<li>'.$key.' '.$count.' with '. $postsPerLanguage[$key] .' posts</li>';
}
?>
</ul>
Your output doesn't need multidimensional array you can achieve it like this:
$final_array = array('Fruits'=> 'orange', 'Furniture'=> 'table')
but for example if you have multiple fruits or furniture you can make something like this:
$final_array = array('Fruits'=> array('orange', 'apple'), 'Furniture'=> array('table', 'sofa'))
and you can access apple like this:
echo $final_array['Fruits'][1];
and for print_r($final_array) we have this:
[Fruits] => (
[0] => orange,
[1] => apple
)
[Furniture] => (
[0] => table,
[1] => sofa
)
Hi All I have 2 arrays for example in PHP as seen below:
[users] => Array ( [0] => Array ( [username] => Timothy ) [1] => Array ( [username] => Frederic ) )
[users2] => Array ( [0] => Array ( [username] => Johnathon ) [1] => Array ( [username] => Frederic ) [] => Array ( [username] => Peter))
I am trying to compare the contents of each array against each other in order to put a html element, I tried using a nested foreach as seen below:
foreach($users as $user){
foreach ($users2 as $user2){
if($user['username'] == $user2['username']){
echo "<option value=' ".$user['username']."' selected = 'selected'>".$user['username']."</option>";
break;
} else{
echo "<option value=' ".$user['username']."'>".$user['username']."</option>";
}
}
}
my issue is that the items are being echoed more than once which is ruining my select element. Any ideas on how to compare the contents of each?
I want to achieve a list of each name eg:
-Timothy
-Frederic (this should be highlighted as it is in both arrays)
-Johnathon
- Peter
I would take it in a different way.
//Create user array one
$users = array();
$users[] = array('username'=>'Timothy');
$users[] = array('username'=>'Frederic');
//create user array 2
$users2 = array();
$users2[] = array('username'=>'Johnathon');
$users2[] = array('username'=>'Frederic');
$users2[] = array('username'=>'Peter');
$temp_array = array();
foreach($users as $key => $value) {
$temp_array[$value['username']] = '';
}
foreach($users2 as $key => $value) {
$temp_array[$value['username']] = array_key_exists($value['username'], $temp_array) ? 'DUPLICATE' : null;
}
echo '<select>';
foreach($temp_array as $key_value => $status) {
echo "<option value='{$key_value}' ".(($status == 'DUPLICATE') ? 'selected style="background-color: yellow;"' : '').">{$key_value}</option>";
}
echo '</select>';
I'll let the array take care of it self, if it shares the same key, it will merge, then just flag it with "duplicate".
If there is never any duplicates as you say in each array, the following works for me. This may look a bit complicated, but read through my comments.
You can copy the code and run it in it's own page to see if it works the way you want.
<?php
//Create user array one
$users = array();
$users[] = array('username'=>'Timothy');
$users[] = array('username'=>'Frederic');
//create user array 2
$users2 = array();
$users2[] = array('username'=>'Johnathon');
$users2[] = array('username'=>'Frederic');
$users2[] = array('username'=>'Peter');
//create a new array to combine all of the data, yes, there will be duplicates
$allData = array();
//add to allData array
foreach ($users as $user) {
$allData[] = $user['username'];
}
//add to allData array
foreach ($users2 as $user2) {
$allData[] = $user2['username'];
}
//create an array that will hold all of the duplicates
$dups = array();
//add any duplicates to the array
foreach(array_count_values($allData) as $val => $c) {
if($c > 1) $dups[] = $val;
}
//remove the duplicates from the allData array
$allData = array_unique($allData);
//echo out form
echo '<select>';
foreach ($allData as $user) {
if (in_array($user, $dups)) {
echo "<option value=' ".$user."' selected = 'selected'>".$user."</option>";
}
else {
echo "<option value=' ".$user."'>".$user."</option>";
}
}
echo '</select>';
?>
However, I'm not sure what your intentions are since IF you had "Peter" and "Frederic" in BOTH arrays, you are not going to get the form you want. But, this works for what you wanted.
I don't understand why the result of the '$taille' array begin to the key [1] instead of key [0]? So it s displaying 3 results instead of 4 (occulting the first result)...
<?php
$req = $bdd->prepare('SELECT size FROM tailles_produits WHERE id_produit = ?');
$req->execute(array($_GET['id']));
$donnees = $req->fetch();
$numb_taille = array();
$taille = array();
$i = 0;
while($donnees = $req->fetch())
{
$i++;
$taille[$i] = $donnees['size'];
$numb_taille['total'] = $i;
}
$total = $numb_taille['total'];
echo '<pre>';
print_r ($taille);
echo '</pre>';
$req->closeCursor();
?>
Which gives
ARRAY
(
[1] => S
[2] => M
[3] => L
)
Instead of
ARRAY
(
[1] => XS
[2] => S
[3] => M
[4] => L
)
Can anyone help me with this pleas?
PHP arrays start with 0, so all you need to do is move your i++ down until after you're done using the data from that index
<?php
$req = $bdd->prepare('SELECT size FROM tailles_produits WHERE id_produit = ?');
$req->execute(array($_GET['id']));
$donnees = $req->fetch();
$numb_taille = array();
$taille = array();
$i = 0;
while($donnees = $req->fetch())
{
$taille[$i] = $donnees['size'];
$numb_taille['total'] = $i;
$i++; //iterate after your calculations are done
}
$total = $numb_taille['total'];
echo '<pre>';
print_r ($taille);
echo '</pre>';
$req->closeCursor();
?>
The problem is that you have an extra
$donnees = $req->fetch();
statement before the loop that fills in $taille. So the data from the first row is being fetched but not stored in the array.
It is because you increment $i before using it as a key for the new array item.
Do the increment at the end of your while loop.
I have an array which comes from a report.
This report has info similar to:
157479877294,OBSOLETE_ORDER,obelisk,19/01/2013 01:42pm
191532426695,WRONG_PERFORMANCE,g3t1,19/01/2013 01:56pm
159523681637,WRONG_PERFORMANCE,g3t1,19/01/2013 01:57pm
176481653889,WRONG_PERFORMANCE,g4t1,19/01/2013 01:57pm
167479810401,WRONG_PERFORMANCE,g4t1,19/01/2013 02:00pm
172485359309,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
125485358802,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
172485359309,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
125485358802,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
What I need to do is get the total of each type of error and the location so for the first would be error: 'OBSOLETE_ORDER' and location: 'obelisk'. I have tried to do this a number of ways but the best I can come up with is a multi dimensional array:
$error_handle = fopen("$reportUrl", "r");
while (!feof($error_handle) )
{
$line_of_text = fgetcsv($error_handle, 1024);
$errorName = $line_of_text[1];
$scannerName = $line_of_text[2];
if($errorName != "SCAN_RESULT" && $errorName != "" && $scannerName != "SCAN_LOGIN" && $scannerName != "")
{
$errorsArray["$errorName"]["$scannerName"]++;
}
}
fclose($error_handle);
print_r($errorsArray);
gives me the following:
Array ( [OBSOLETE_ORDER] => Array ( [obelisk] => 1 ) [WRONG_PERFORMANCE] => Array ( [g3t1] => 2 [g4t1] => 2 [g4t2] => 2 ) [DAY_LIMIT_EXCEEDED] => Array ( [obelisk] => 2 ) )
which is great...except how do I then take that apart to add to my sql database?! (I am interested in getting the key and total of that key under the key the array is under)
and then add it to the tables
-errors-
(index)id_errors
id_event
id_access_scanner
id_errors_type
total_errors
-errors_type-
(index)id_errors_type
name_errors_type
-access_scanner-
(index)id_access_scanner
id_portal
name_access_scanner
PLEASE HELP!
Thanks!
A multidimensional array is more than you need. The approach to take is to create your own string ($arrayKey in my example) to use as an array key that combines the scanner name and the error so that you can get a count.
//this is the array containing all the report lines, each as an array
$lines_of_text;
//this is going to be our output array
$errorScannerArray = array();
//this variable holds the array key that we're going to generate from each line
$arrayKey = null;
foreach($lines_of_text as $line_of_text)
{
//the array key is a combination of the scanner name and the error name
//the tilde is included to attempt to prevent possible (rare) collisions
$arrayKey = trim($line_of_text[1]).'~'.trim($line_of_text[2]);
//if the array key exists, increase the count by 1
//if it doesn't exist, set the count to 1
if(array_key_exists($arrayKey, $errorScannerArray))
{
$errorScannerArray[$arrayKey]++;
}
else
{
$errorScannerArray[$arrayKey] = 1;
}
}
//clean up
unset($line_of_text);
unset($arrayKey);
unset($lines_of_text);
//displaying the result
foreach($errorScannerArray as $errorScanner => $count)
{
//we can explode the string hash to get the separate error and scanner names
$names = explode('~', $errorScanner);
$errorName = $names[0];
$scannerName = $names[1];
echo 'Scanner '.$scannerName.' experienced error '.$errorName.' '.$count.' times'."\n";
}
$list = array();
foreach ($lines as $line) {
$values = explode(',' $line);
$error = $values[1];
$scanner = $values[2];
if (!isset($list[$error])) {
$list[$error] = array();
}
if (!isset($list[$error][$scanner])) {
$list[$error][$scanner] = 1;
} else {
$list[$error][$scanner]++;
}
}
To go through each result I just did the following:
foreach ($errorsArray as $errorName=>$info)
{
foreach ($info as $scannerName=>$total)
{
print "$errorName -> $scannerName = $total </br>";
}
}
and now will just connect it to the sql
With your edited question, this much simpler loop will work for you, you just need to then insert the data into your database inside the loop, instead of echoing it out:
$errorsArray = Array (
[OBSOLETE_ORDER] => Array (
[obelisk] => 1
)
[WRONG_PERFORMANCE] => Array (
[g3t1] => 2
[g4t1] => 2
[g4t2] => 2
)
[DAY_LIMIT_EXCEEDED] => Array (
[obelisk] => 2
)
)
foreach($errorsArray as $row => $errors) {
foreach($errors as $error => $count) {
echo $row; // 'OBSOLETE_ORDER'
echo $error; // 'obelisk'
echo $count; // 1
// insert into database here
}
}
OLD ANSWER
You just need a new array to hold the information you need, ideally a count.
Im assuming that the correct data format is:
$report = [
['157479877294','OBSOLETE_ORDER','obelisk','19/01/2013 01:42pm'],
['191532426695','WRONG_PERFORMANCE','g3t1','19/01/2013 01:56pm'],
['159523681637','WRONG_PERFORMANCE','g3t1','19/01/2013 01:57pm'],
['176481653889','WRONG_PERFORMANCE','g4t1','19/01/2013 01:57pm'],
.....
];
foreach($report as $array) {
$errorName = $array[1];
$scannerName = $array[2];
if(exists($errorsArray[$errorName][$scannerName])) {
$errorsArray[$errorName][$scannerName] = $errorsArray[$errorName][$scannerName] + 1;
}
else {
$errorsArray[$errorName][$scannerName] = 1;
}
}