How i can output my array without quotes on this situation
for($i=1; $i <= date("d"); $i++) { $days[] = $i; }
echo json_encode($days); // ouput [1,2,3,4,5,6,7,8,9,10]
This first on is fine, but on the second one
for($i=1;$i <= date("d"); $i++) {
$Sql = "SELECT COUNT(Stats_Clicks) AS Total FROM tabstats WHERE DAY(Stats_Date) = $i
AND MONTH(Stats_Date) = $month
AND YEAR(Stats_Date) = $year
";
$Query = mysql_query($Sql,$Conn) or die (mysql_error($Conn));
$Rs = mysql_fetch_array($Query);
$clicks[] = $Rs['Total'];
}
echo json_encode($clicks);
json output returns this
["1","1","0","0","0","0","0","0","0","0","0"]
i need this without quotes on this format.
You just need cast to integer.
$clicks[] = (int)$Rs['Total'];
Untested:
$clicks[] = (int) $Rs['Total'];
try array_map with intval function
like this:
echo json_encode(array_map("intval",($Rs['Total'])));
example:
print_r(json_encode(array_map("intval",array("1","2","3"))));
=> [1,2,3]
Related
I have an array which has nested String that I want to output without a loop.
Here is the array:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
I want to output this as
First, Second, Third, Forth, Fifth
This is what I tried (but it's in loop)
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
I'd be inclined to break this down into two parts:
Convert the array into a simplified version that just contains the values you want to concatenate. For that, you can use array_map() (https://www.php.net/manual/en/function.array-map.php).
Join the elements of the array without an extra comma on the end. The perfect use case for implode() (https://www.php.net/manual/en/function.implode.php).
Example:
echo implode(', ', array_map(function($item) {
return $item['string_term']->name;
}, $field_my_array));
I am not sure what you're trying to achieve. If you don't want to loop, then you have to manually write like this:
echo $field_my_array[0]['string_term']->name;
echo ", ";
echo $field_my_array[1]['string_term']->name;
...
and so on. Looping is a fundamental programming construct that allows us to automate with a simple count.
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
A better one would be this:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
$names = array();
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
$names[] = $field_my_array[$ctr]['string_term']->name;
}
// this creates a string with a comma between items from array
$full_text = implode(', ',$names);
echo $full_text ;
You can use array_merge_recursive with implode
$c = array_merge_recursive(...$field_my_array);
echo implode(',', $c['string_term']['name']);
Live DEMO https://3v4l.org/GdhM5
This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 6 months ago.
Good Day!
Any suggestions on how can I merged and print 3 arrays in PHP.
I retrieved data from database and put it in ARRAY.
1st Array: $date[] = $row['date'];
2nd Array: $requestor[] = $row['requestor'];
3rd Array: $die[] = $row['die'];
then I use foreach to print the retrieved data stored from each Array that meets the condition.
foreach($date as $item_date){
echo $item_date;
}
foreach($requestor as $item_requestor){
echo $item_date;
}
foreach($die as $item_die){
echo $item_requestor;
}
But the result of this code is like this:
date1
date2
date3
requestor1
requestor2
requestor3
die1
die2
die3
My goal is this one:
date1 - requestor1 - die1
date2 - requestor2 - die2
date3 - requestor3 - die3
Any Idea oon how can I achieved this output.
TIA
You have to do it manually count on loop like this
$count = count($date)-1;
then loop through this
for ( $i=0;$i <= $count; $i++ ) {
$arrayGenerate[$i] = array(
'row1' => $data[$i].'-'.$requestor[$i].'-'.$die[$i]
);
}
like this
Try with -
for($i = 0; $i <= count($date); $i ++) {
echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
}
Assuming the all 3 arrays count/size is same & you want it in this fashion
<?php
$a = array('1','2','3');
$b = array('4','5','6');
$c = array('7','8','9');
for($i=0;$i<count($a);$i++)
{
echo $merged_arr_str = $a[$i] . " - " . $b[$i] . " - ". $c[$i] . " <br/>";
}
?>
You can try this
Example One:-
$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');
$count = max(count($date), count($requestor), count($die));
$newarray = array();
for($i=0; $i < $count; $i++) {
//Demo1
if (isset($date[$i])) $newarray[] = $date[$i];
if (isset($requestor[$i])) $newarray[] = $requestor[$i];
if (isset($die[$i])) $newarray[] = $die[$i];
//Demo2
//echo $ouput = $date[$i].'-'.$requestor[$i].'-'.$die[$i];
}
//array merge output
var_dump($newarray);
Example Two
$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');
$arrays = array($date, $requestor, $die);
array_unshift($arrays, null);
$n = call_user_func_array('array_merge', call_user_func_array('array_map', $arrays));
print_r($n);
for($i = 0; $i < count($date); $i ++) {
echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
}
this loop will iterat untill last element of date array.if you want to put equal to sign then you have to initialize $i with 1.
exm. if $i = 0 then $i < count($date)
OR
if $i = 1 then $i <= count($date)
I am trying to query a database with a new 'WHERE (AND)' clause on each loop. The new clause is simply the number of the loop.
I need to save the count of rows returned per loop in an array which I am struggling with.
If for instance there is two loops, the first loop returns 2 rows, the second 3. I want the array to essentially be:
$portfolio_list = array(2,3);
Here is as far as I have managed to get, and no surprise its not working correctly.
Any help would be great!
$portfolios = 2;
$i = 1;
$portfolios_list = array();
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->EE->db->query($portfolio_sql);
$return = $query->result();
$portfolios_list[] = $return;
$i++;
}
please try this
$portfolios = 2;
for ($i = 1; $i < $portfolios+1; $i++) { //this runs 2 times
$where_array = array('member_id' => $member_id, 'type_id' => '1', 'portfolio_number' => $i);
$this->db->where( $where_array );
//$this->db->select('*'); // I guess you do not need select for this
$portfolio_list[$i] = $this->db->get('exp_submissions')->num_rows();
}
var_dump($portfolio_list);
Try this
$portfolios = 2;
$i = 1;
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->db->query($portfolio_sql);
$portfolios_list[$i] = $query->num_rows; // This will give the No of rows fetched
$i++;
}
foreach($portfolios_list as $row => $no)
{
echo "The Results Fetched from query no ".$row." is ".$no;
}
I am trying to get a series of 'titles' from a database, and place them in an array as individual strings for each title. Currently I am using this code
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$totalRows_getLatest = mysql_num_rows($getLatest);
$latestNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
}
and when I call them individually using
echo $latestNews[0][0];
I get the string value.
However, I would like to place these strings in to a single array, thereby generating an array of strings. I have tried this:
$latestNews = array();
$extractNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
$extractNews[] = $latestNews[i][0];
}
but it doesn't return the string in the output extractNews array.
What am I doing wrong?
Thanks
Is this what you are looking for?
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$latestNews = array();
while($row = mysql_fetch_assoc($getLatest)) {
$latestNews[] = $row['title'];
}
echo "<pre>" . print_r($latestNews,1) . "</pre>";
WATCH OUT
Please do not use the mysql_* functions anymore. They are deprecated and won't be supported in >= php 5.5. Switch to mysqli_* or PDO.
I know how to execute php variable inside quotes
$q1 = 1;
$q2 = 2;
$q3 = 3;
$q4 = 4;
$q5 = 5;
echo "${q1}"; //outputs 1
How can i output them in a loop?
for($i=1; $i<=5; $i++)
{
echo "${q$i}"; //how to make $i work here?
}
How to make $i work along with $q?
UPDATE
i want the quotes to be there, because i am creating a string in a loop and i want to pass that loop to mysql query. So i want the string to be like
$str = '$q1, $q2, $q3';
and when i pass it to mysql query it should interpret the values of $q1, $q2, $q3 which is 1,2,3
mysql_query("INSERT INTO users (col1, col2, col3) VALUES ($str)");
So it should become
mysql_query("INSERT INTO users (col1, col2, col3) VALUES (1,2,3)");
It is just an example i know the syntax of mysql_query is wrong but you know
I think what you are looking for is this:
<?php
$arr = array();
$q1 = 1;
$q2 = 2;
$q3 = 3;
$q4 = 4;
$q5 = 5;
for($i=1; $i<=5; $i++)
{
$arr[] = ${"q".$i};
}
$str = implode($arr, ',');
print_r($str);
Outputs:
1,2,3,4,5
In action: http://codepad.org/ep7sraT5
for($i=1; $i<=5; $i++)
{
$x = "q$i";
echo $$x;
}
works!
Use this code, it should work :)
echo ${"q${i}"};
The double quotes around the whole thing are useless
use
echo ${'q' . $i};
EDIT: If you want to create the comma seperated string, why not try
$q1 = 1;
$q2 = 2;
$q3 = 3;
$q4 = 4;
$q5 = 5;
$parts = array();
for($i=1; $i<=5; $i++)
{
$parts[] = ${'q' . $i};
}
$str = implode(', ', $parts);
Also consider escaping the values before running the MYSQL, you could do this within the for loop before adding the value to the $parts array
for($i=1; $i<=5; $i++)
{
echo ${"q".$i};
}
Output:
12345
Codepad: http://codepad.org/2PIshh41
UPDATE:
Since you wanted to store the value in varible, you can do this:
$str = '';
for($i=1; $i<=5; $i++)
{
$str .= "${"q".$i}, ";
}
$str = rtrim($str, ' ,'); //trim last comma
mysql_query("INSERT INTO users (col1, col2, col3) VALUES ($str)");
//becomes mysql_query("INSERT INTO users (col1, col2, col3) VALUES (1, 2, 3, 4, 5)")
Hope this helps!