Echo value in array_push - php

I have this code:
include "xmlapi.php";
$pass = 'testing1234';
$auser = 'testing';
$server = "0.0.0.0";
$port = 2087;
$remote_api = new xmlapi($server);
$remote_api->password_auth($auser, $pass);
$remote_api->set_port($port);
$remote_api->set_output('json');
$json_list = $remote_api->xmlapi_query('listaccts', array( 'api.version'=> 1));
$list = json_decode($json_list, true);
if ( ! is_array($list)
|| ! array_key_exists('data', $list)
|| ! is_array($list['data'])
|| ! array_key_exists('acct', $list['data'])
) {
die("Invalid response!");
}
$email_list = array();
foreach ($list['data']['acct'] as $acct) {
$username = $acct['user'];
$json_emails = $remote_api->api2_query($username, 'Email', 'listpopswithdisk', array());
$acct_emails = json_decode($json_emails, true);
if ( is_array($acct_emails)
&& array_key_exists('cpanelresult', $acct_emails)
&& is_array($acct_emails['cpanelresult'])
&& array_key_exists('data', $acct_emails['cpanelresult'])
&& is_array($acct_emails['cpanelresult']['data'])
) {
foreach ($acct_emails['cpanelresult']['data'] as $an_email) {
array_push(
$email_list,
array(
'cpanel_account' => $username,
'domain' => $an_email['domain'],
'email' => $an_email['user'],
'full_email' => $an_email['email'],
'diskused' => $an_email['diskused'],
)
);
echo $an_email['email'] . ' - ';
echo $an_email['diskused'] . ' - ';
echo $an_email['user'] . '<br>';
}
}
}
I used this code to connect to my cpanel and list all the email on the server.
At first I just use var_dump to see if it works. And tried to use foreach loop but not success.
How can I do a loop to echo all the data, so I can put the data in a table or something like that.
Please help me with this, thank you.

You need to parse the array containing the email accounts and print into a <table>
Try to adapt this code:
$email_list = [
['email' => 'first#email.com', 'diskused' => 'the diskused', 'user' => 'the first user'],
['email' => 'second#email.com', 'diskused' => 'the diskused', 'user' => 'the second user'],
['email' => 'third#email.com', 'diskused' => 'the diskused', 'user' => 'the third user'],
];
if (count($email_list)) {
print '<table>';
/* Set the header fields to print and Titles */
$headers = [
'email' => 'Email',
'diskused' => 'Diskused',
'user' => 'User'
];
/* Print table headers */
print '<tr>';
foreach ($headers as $headerTitle) {
print '<th>'.$headerTitle.'</th>';
}
print '</tr>';
/* Parse all rows */
foreach ($email_list as $row) {
print '<tr>';
/* Print all values */
foreach (array_keys($headers) as $headerKey) {
print '<td>'.$row[$headerKey].'</td>';
}
print '</tr>';
}
print '</table>';
}

Related

php dynamic table from muldimentional array

can you give me idea how to implement this idea for "dynamic" html table.
I have an array
$arr = array(
array(
'label' => 'First name',
'data' => array(
array('fname' => 'John'),
array('fname' => 'Ralph'),
),
),
array(
'label' => 'Last name',
'data' => array(
array('lname' => 'Doe'),
array('lname' => 'Loren'),
),
),
array(
'label' => 'Description',
'data' => array(
array('description' => 'Something bout John'),
array('description' => 'Something about Ralph'),
),
),
);
Now from the keys 'label' im creating the table columns
---------------------------------------
|First Name | Last Name | Description |
---------------------------------------
The problem is how to put 'fname' keys in the first column, 'lname' in the second and 'description' in the third.
With this part of code im trying to put the data in all columns
private function tableBody()
{
$data = $this->data;
$table = '<tbody>';
foreach($data as $key => $value){
foreach($value['data'] as $k => $v){
$table .= '<tr>';
foreach($v as $col => $name){
$table .= '<td>' . $name . '</td>';
}
$table .= '</tr>';
}
}
$table .= '</tbody>';
return $table;
}
Also my idea is not to hard code array keys for multiple usage(except label and data).
First I would remap the data to process it in loops.
$labels = [];
$rows = [];
foreach($arr as $column) {
$label = $column['label'];
$labels[] = $label;
foreach($column['data'] as $key => $value) {
$rows[$label][] = $value;
}
}
Now print out the labels with the headline.
echo "<table>\n";
echo "<tr>";
foreach($labels as $label) echo "<th>{$label}</th>";
echo "</tr>\n";
Iterate through the rows and create the HTML.
$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);
while($rowCount) {
echo "<tr>";
for ($i = 0; $i < $labelCount; $i++) {
$current = array_shift($rows[$labels[$i]]);
$value = reset($current);
echo "<td>{$value}</td>";
}
echo "</tr>\n";
$rowCount--;
}
echo "</table>\n";
This gives a table like below
<table>
<tr><th>First name</th><th>Last name</th><th>Description</th></tr>
<tr><td>John</td><td>Doe</td><td>Something bout John</td></tr>
<tr><td>Ralph</td><td>Loren</td><td>Something about Ralph</td></tr>
</table>
You need to manipulate the initial array to reduce it to something more manageable. You could brute force your way like so:
function reduce($data) {
$ret = [];
foreach ($data as $d1) {
// column header could have been fetched here
foreach ($d1 as $k2 => $d2) {
// keeping track of what label we need
$key = '';
// keeping the values together
$child = [];
// discarding non arrays
if (is_array($d2)) {
foreach ($d2 as $d3) {
// identifier fetch from this level
foreach ($d3 as $k4 => $d4) {
$key = $k4;
$child[] = $d4;
}
}
}
// assigning back to the main array only if we have something
if (!empty($child)) {
$ret[$key] = $child;
}
}
}
return $ret;
}
That will return the following:
Array
(
[fname] => Array
(
[0] => John
[1] => Ralph
)
[lname] => Array
(
[0] => Doe
[1] => Loren
)
[description] => Array
(
[0] => Something bout John
[1] => Something about Ralph
)
)

How to auto increment in sub foreach loop?

Here is the example code:
<?php
$arr = array(
array(
'company' => array(
'code' => 'ccd1',
'name' => 'cnm1'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
)
)
) ,
array(
'company' => array(
'code' => 'ccd2',
'name' => 'cnm2'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
) ,
array(
'code' => 'pcd3',
'name' => 'pnm3'
)
)
)
);
echo "<pre>"; print_r($arr); echo "</pre>";
$AI = 1;
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
foreach($value['products'] as $value2){
echo " ".$value2['name']."<br />";
}
}
I don't know how to explain it, but what I want is to add auto increment in sub foreach loop, like this:
1.cnm1 (2)
1.pnm1
2.pnm2
2.cnm2 (3)
1.pnm1
2.pnm2
3.pnm3
Usually you can just use the foreach keys plus one. As another alternative, if this is just for presentation, just use ordered lists:
echo '<ol>';
foreach($arr as $ar1) {
echo '<li>' . $ar1['company']['name'] . ' (' . count($ar1['products']) . ')</li>';
echo '<ol>';
foreach($ar1['products'] as $ar2) {
echo "<li>{$ar2['name']}</li>";
}
echo '</ol>';
}
It'll number those items accordingly. No need for addition. Plus you can use CSS to style the list,
You can access the key/index of an foreach :
foreach($arr as $i => $value){
$total_products = count($value['products']);
echo ($i+1).'.'.$value['company']['name'].' ('.$total_products .')<br />';
foreach($value['products'] as $j => $value2){
echo ' '.($j+1).'.'.$value2['name'].'<br />';
}
}
Here you go.
$arr = array(array('company'=>array('code'=>'ccd1', 'name'=>'cnm1'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'))), array('company'=>array('code'=>'ccd2', 'name'=>'cnm2'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'), array('code'=>'pcd3', 'name'=>'pnm3'))));
echo "<pre>";
print_r($arr);
echo "</pre>";
$AI = 1;
foreach($arr as $value)
{
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$k = 0;
foreach($value['products'] as $value2)
{
echo " ".$k++.". ".$value2['name']."<br />";
}
}
This also worked for me:
foreach($value['products'] as $key2=>$value2){
$AI2 = $key2+1;
echo " ".$AI2.".{$value2['name']}<br />";
}
You can try this:
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$sub=1;
foreach($value['products'] as $value2){
echo " ".$sub++.'.'.$value2['name']."<br />";
}
}

PHP: Array with foreach loop?

I have a and Array which looks like this:
$sms = array(
'from' => 'DummyFrom',
'to' => '+46709751949',
'message' => 'Hello hello!'
);
echo sendSMS ($sms) . "\n";
what i'm trying to do is to put this array within a foreach loop so it can be executed multiple time (based on the given times from mysql database). to explain it better, I did something like this:
if (is_array($g_numbers)) {
foreach ($g_numbers as $number) {
$sms = array(
'from' => 'DummyFrom',
'to' => "" . $number . "",
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}
but that is wrong and its stops the PHP page to execute properly without any errors!
Could someone please advise on this issue?
My full code :
<?php
$people = array();
$sql = "SELECT id, g_name, numbers FROM groups WHERE g_name='$groups'";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$g_id = $row['id'];
$g_name = $row['g_name'];
$g_numbers = $row['numbers'];
$people[$g_numbers] = $g_numbers;
}
?>
<?
// Example to send SMS using the 46elks service
// Change $username, $password and the mobile number to send to
function sendSMS($sms)
{
// Set your 46elks API username and API password here
// You can find them at https://dashboard.46elks.com/
$username = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$password = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic " . base64_encode($username . ':' . $password) . "\r\n" . "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($sms),
'timeout' => 10
)
));
$response = file_get_contents('https://api.46elks.com/a1/SMS', false, $context);
if (!strstr($http_response_header[0], "200 OK"))
return $http_response_header[0];
return $response;
}
if (is_array($g_numbers)) {
foreach ($g_numbers as $number) {
$sms = array(
'from' => 'DummyFrom',
/* Can be up to 11 alphanumeric characters */
'to' => "" . $number . "",
/* The mobile number you want to send to */
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}
?>
This will work because tables values are stored in $people:
if (is_array($people)) {
foreach ($people as $number) {
$sms = array(
'from' => 'DummyFrom',
/* Can be up to 11 alphanumeric characters */
'to' => "" . $number . "",
/* The mobile number you want to send to */
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}

how to remove last comma (,) from this string without using built-in functions like "rtrim" and "substr"

How to remove last comma (,) from array?
without using inbuilt functions like rtrim and substr
public function update( $table_name="", $fields_value=array(), $where="" ){
//if( $table_name == "" || empty($fields_value) || $where == "" ) return false;
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$column_value_string = "";
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string .= " `$col_name`='$col_value' ,";
}
echo rtrim($column_value_string,",")."<br><br><br><br>";
return;
To create a comma-seprated list, put things into an array and then implode it:
$column_value = array();
foreach( $fields_values as $col_name => $col_value ) {
$column_value []= "`$col_name`='$col_value'";
}
$column_value_string = implode(", ", $column_value);
Also do note that you must escape values when generating SQL commands dynamically.
You can done this with counter in your loop Try
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$count = count($fields_values);
$i=1;
$column_value_string = "";
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string .= " `$col_name`='$col_value'";
if($i <$count) {
$column_value_string .= ',';
}
$i++;
}
echo $column_value_string;
output :-
`name`='Vikrant', `class`='MCA', `Section`='a', `Subject`='Ele'
$array = explode(",",$ TheArray);
$array = implode(",", $array);
Short, simple.. does the trick
<?php
$str = 'test,';
if($str[strlen($str) - 1 ] == ',') $str[strlen($str) - 1] = null;
echo $str; // test
?>
Hope this will help you......
public function update( $table_name="", $fields_value=array(), $where="" ){
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$column_value_string = array();
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string[] = " `$col_name`='$col_value'";
}
echo implode(',',$column_value_string);
You can achieve desired result by following
public function update( $table_name="", $fields_value=array(), $where="" ){
//if( $table_name == "" || empty($fields_value) || $where == "" ) return false;
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$column_value_string = "";
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string .= ($column_value_string == ""?'':', ')." `$col_name`='$col_value'";
}
echo $column_value_string."<br><br><br><br>";
return;
}

PHP - Arrays and Foreach

I searched in Google and consulted the PHP documentation, but couldn't figure out how the following code works:
$some='name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
return $addons;
}
echo (count( getActiveAddons( $some ) ) ? implode( '<br />', getActiveAddons( $some ) ) : 'None');
The code always echo's None.
Please help me in this.
I don't know where you got this code from but you've initialized $some the wrong way. It is expected as an array like this:
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon'
'nextduedate' => '2013-04-11',
'status' => 'Active'
)
);
I guess the article you've read is expecting you to parse the original string into this format.
You can achieve this like this:
$string = 'name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
$result = array();
foreach(explode('|', $string) as $record) {
$item = array();
foreach(explode(';', $record) as $column) {
$keyval = explode('=', $column);
$item[$keyval[0]] = $keyval[1];
}
$result[]= $item;
}
// now call your function
getActiveAddons($result);
$some is not an array so foreach will not operate on it. You need to do something like
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon',
'nextduedate' => '2013-04-11',
'status'=> 'Active'
)
);
This will create a multidimensional array that you can loop through.
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
foreach($addon as $key => $value) {
if ($key == 'status' && $value == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
}
return $addons;
}
First, your $some variable is just a string. You could parse the string into an array using explode(), but it's easier to just start as an array:
$some = array(
array(
"name" => "Licensing Module",
"nextduedate" => "2013-04-10",
"status" => "Active",
),
array(
"name" => "Test Addon",
"nextduedate" => "2013-04-11",
"status" => "Active",
)
);
Now, for your function, you are on the right track, but I'll just clean it up:
function getActiveAddons($somet) {
if (!is_array($somet)) {
return false;
}
$addons = array();
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
}
}
if (count($addons) > 0) {
return $addons;
}
return false;
}
And finally your output (you were calling the function twice):
$result = getActiveAddons($some);
if ($result === false) {
echo "No active addons!";
}
else {
echo implode("<br />", $result);
}

Categories