I have a simple JSON StdClass Object from a PHP, and I wish to format it into a table/list/div and eliminate other keys and values in the process. The JSON looks like this:
stdClass Object (
[msc] => 150
[number] => 309
[status] => OK
[msc_mcc] => 652
[imsi] => 652010154107728
[mcc] => 652
[operator_country] => Botswana
[msc_operator_name] => MSC
[msc_operator_country] => Botswana
[msc_mnc] => 01
[mnc] => 01
[id] => 1072540715
[msc_location] =>
[operator_name] => MSC )
I have tried PHP and did make a table, but the problem is I need to pick certain values other that the whole body, and also I need to eliminate empty values
function print_nice($elem,$max_level=10,$print_nice_stack=array()){
if(is_array($elem) || is_object($elem)){
if(in_array($elem,$print_nice_stack,true)){
echo "<font color=red>RECURSION</font>";
return;
}
$print_nice_stack[]=&$elem;
if($max_level<1){
echo "<font color=red>nivel maximo alcanzado</font>";
return;
}
$max_level--;
echo "<table class='table table-bordered table-striped'>";
if(is_array($elem)){
echo '<tr><th colspan=2><strong><font><h3>Results, with love</h3></font></strong></th></tr>';
}else{
echo '<tr><th colspan=2 class=hdrs><strong>';
echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></th></tr>';
}
$color=0;
foreach($elem as $k => $v){
if($max_level%2){
$rgb=($color++%2)?"#f5f5f5":"#efeeee";
}else{
$rgb=($color++%2)?"#f5f5f5":"#efeeee";
}
echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
echo '<strong>'.$k."</strong></td><td>";
print_nice($v,$max_level,$print_nice_stack);
echo "</td></tr>";
}
echo "</table>";
return;
}
if($elem === null){
echo "<font color=green>NULL</font>";
}elseif($elem === 0){
echo "0";
}elseif($elem === true){
echo "<font color=green>TRUE</font>";
}elseif($elem === false){
echo "<font color=green>FALSE</font>";
}elseif($elem === ""){
echo "<font color=green>EMPTY STRING</font>";
}else{
echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
}
}
get_object_vars() and in_array() may be helpful here
For example:
<?php
$object = json_decode($jsonstring);
?>
<table>
<?php
foreach (get_object_vars($object) as $k => $v)
{
if (in_array($k, array('msc', 'number', 'status')) && ! empty($v))
{
echo '<tr>';
echo "<td>{$k}</td><td>{$v}</td>";
echo '</tr>';
}
}
?>
</table>
Where $object is the name of your json_decoded variable
Edit:
Added a check for empty values too
Related
I'm not too sure how to call the Associative array to verify if the number is true or false because I am doing a simple checker for enrollment class. The max class capacity is 40 and the file is combined with HTML and PHP.
I did it like this:-
<?php
//Create the association array.
$classInfo = array("J1" => 20 ,"J2" => 30,"J3" => 10,"J4" => 43,
"J5" => 40,"J6" => 45,"J7" => 15,"J8" => 34,"J9" => 10,"J10" => 45);
$class = array_keys($classInfo);
$totalEnroll = count($classInfo);
?>
The Code:-
<table width="300" style="border: 1px solid black">
<tr>
<?php
// class and enroll Lists
echo "<td width=20>";
echo "Class"."        "." Enroll"."<br><hr>";
for($i=0; $i < $totalEnroll; ++$i) {
echo $class[$i] . "     " .
$classInfo[$class[$i]] . "<br>";
}
echo "</td>";
// Enroll to check whether the classroom is full.
echo "<td width=20>";
echo "Class States" . "<br><hr>";
for($check = 0; $check < 10; $check++){
if($classInfo[$totalEnroll[$check]] >= 0 &&
$classInfo[$totalEnroll[$check]] <= 40){
echo "Full";
echo " <br>";
} else {
echo "Not Full";
echo " <br>";
}
}
echo "</td>";
?>
</tr>
</table>
The Output That I want:-
Class
Enroll
Full States
J1
20
Not Full
J5
40
Full
Do check on the part say `//Enroll to check whether the classroom is full. This is where the code of the enrollment class is checked.
However, by the way, the output can it be aligned more cleanly in a table-like column.
You are displaying the data in two separate loops which makes it difficult to align the data, you should make it into 1 loop and use the <tr> and <td> tags around each group of items...
<table width="300" style="border: 1px solid black">
<?php
foreach ( $classInfo as $className => $enrolled ) {
echo "<tr>";
// class and enroll Lists
echo "<td>{$className}</td>";
echo "<td>{$enrolled}</td>";
// Enroll to check whether the classroom is full.
echo "<td>";
if($enrolled <= 40){
echo "Full";
} else {
echo "Not Full";
}
echo "</td>";
echo "</tr>";
}
?>
</table>
(This doesn't include a header, but I'm sure you can add that).
i have a cookie that i stored an array of values inside it. now when i try to access the information by the name of the cookies it keeps giving me the error "ILLEGAL STRING OFFSET". i dont understand what this error means in my situation.
what am i doing wrong?
why cant i access the details with the name of the cookie?
here is my code:
if (isset($_POST['save_details'])) {
if (isset($_COOKIE['historyDetails'])) {
$read_cookie=json_decode($_COOKIE['historyDetails']);
$cookieValue=$read_cookie;
}
$details['totalsalary_cookie'] = $total_salary;
if (isset($extra)) {
foreach($extra as $e){
$details=explode("#",$e);
$name=$details;
$details['extras_cookie']= $name;
}
}
$details['date_cookie']= date("d/m/y");
$details['time_cookie']= date("h:i:sa");
$cookieValue =$details;
setcookie("historyDetails", json_encode($cookieValue), $one_week);
}
echo "<ul>";
echo "<li>Salary details: Total salary is BD $total_salary";
if (count($extra_names)>0) {
echo "<li>Extras:</li>";
echo "<ol type = "."1".">";
for ($i=0; $i <count($extra_names) ; $i++) {
echo "<li>$extra_names[$i]</li>";
} echo "</ol>";
}
echo "</ul>";
die("</body></html>");
}elseif (isset($view_history)) {
//echo $_COOKIE["historyDetails"];
//print_r($_COOKIE);
?>
<table align="center" border="1">
<tr>
<th>Total Salary</th>
<th>Date</th>
<th>Time</th>
<th>Extras</th>
</tr>
<?php
if(isset($_COOKIE["historyDetails"])){
echo "<tr>";
echo "<td align=center>".$_COOKIE["historyDetails"]["totalsalary_cookie"]."</td>";
echo "<td align=center>".$_COOKIE["historyDetails"]["date_cookie"]."</td>";
echo "<td align=center>".$_COOKIE["historyDetails"]["time_cookie"]."</td>";
if(isset($_COOKIE["historyDetails"])){
echo "<td align=center>";
echo "<ul>";
$emp=explode("#",$_COOKIE["historyDetails"]["extras_cookie"]);
echo "<li>".$emp."</li>";
echo "</ul>";
echo "</td>";
}
else{
echo "<td align=center>"."No extras Found!"."</td>";
}
echo "</tr>";
}
die();
}
?>
any help?
Without knowing the content you are trying to set in the cookie I had to improvise to test this code. In my tests the contents of the cookie were urlencoded which is why - in conjunction with the fact that the value is json encoded, I suspect, you were not able to directly access the values held within the cookie by name.
<?php
$_POST['save_details']=true;
$cname='historyDetails';
$one_week=strtotime( 'now + 1 week' );
$total_salary=mt_rand(150000,250000);
$extra=array(
'banana' => 'yellow#curvy#healty',
'snow' => 'cold#white#fun'
);
if ( isset( $_POST['save_details'] ) ) {
if( isset( $_COOKIE[ $cname ] ) ) {
$cookieValue=json_decode( $_COOKIE[ $cname ] );
}
$details['totalsalary_cookie'] = $total_salary;
if( isset( $extra ) ) {
foreach( $extra as $e ){
$details=explode("#",$e);
$name=$details;
$details['extras_cookie']= $name;
}
}
$details['date_cookie']= date("d/m/y");
$details['time_cookie']= date("h:i:sa");
$cookieValue=$details;
setcookie( $cname, json_encode( $cookieValue, JSON_HEX_APOS ), $one_week );
}
if( isset( $_COOKIE['historyDetails'] ) ){
$json=json_decode( urldecode( $_COOKIE[ $cname ] ) );
printf('<pre>%s</pre>',print_r($json,true));
}
?>
This yields a cookie string like this:
%7B%220%22%3A%22cold%22%2C%221%22%3A%22white%22%2C%222%22%3A%22fun%22%2C%22extras_cookie%22%3A%5B%22cold%22%2C%22white%22%2C%22fun%22%5D%2C%22date_cookie%22%3A%2220%5C%2F03%5C%2F21%22%2C%22time_cookie%22%3A%2201%3A10%3A27pm%22%7D
But when decoded using the code shown yields:
stdClass Object
(
[0] => cold
[1] => white
[2] => fun
[extras_cookie] => Array
(
[0] => cold
[1] => white
[2] => fun
)
[date_cookie] => 20/03/21
[time_cookie] => 01:09:25pm
)
From that you should find it is easy enough to access items from the cookie:
echo $json->extras_cookie[0], $json->date_cookie; //etc
i have a multidimensional array like this
$role = array (
'Dashboard' => null,
'Students' =>
array (
'Admission' => array ( 0 => 'Entry' ,1 => 'Review' , 2 => 'Approved/Reject'
),
'Search' => null,
'AdvanceSearch' => null,
'Courses' => null
),
'HR' => array ('Settings' => null),
'Employee Management' => array ( 0 => 'Entry',1 => 'Association',2 => 'Search' ),
'Employee Attendance' => null,
'Payroll' => array (0 => 'Generate Pay Slip',1 => 'Payroll Run' , 2 => 'Payroll Revert',3 => 'View Pay Slips'),
'Finance' => null,
'More' => null);
and i want to print this array result in my html as
i am trying to do this by using recursion but unable to do that as DIV are not properly closed ..
here is the code that i am trying in my html
<?php
$child = 0;
function RecursiveWrite($array, $child ) {
$parent_array_size = count($array);
foreach ($array as $key => $vals) {
if(is_array($vals)){
$inner_array_size = count($vals);
echo "<div class='main clear'><input type='checkbox'/> ".$key." ";
RecursiveWrite($vals,$child);
}else{
$child = 0;
if(is_numeric($key)){
echo " <div class='left'> <input type='checkbox' class=''/> ".$vals." </div></div>";
}else{
echo "<div class='clear'><input type='checkbox'/> ".$key." </div></div>";
}
}
//
}
}
RecursiveWrite($role, $child);
?>
here is working code
How can i get this Any suggestion ... ?
Your Problem is missing closing div after recursion
Try this Function
function RecursiveWrite($array, $child )
{
$parent_array_size = count($array);
foreach ($array as $key => $vals)
{
if(is_array($vals))
{
$inner_array_size = count($vals);
echo "<div class='deep'><div class='extra'><input type='checkbox'/> ".$key."</div>";
RecursiveWrite($vals,$child);
echo "</div>";
}
else
{
if(is_numeric($key)){
echo "<span class='single'><input type='checkbox' class=''/> ".$vals."</span>";
}else{
echo "<div class='single'><input type='checkbox'/> ".$key." </div>";
}
}
}
}
Use This Css
<style type="text/css">
.parent {border: solid 1px #000;}
.parent div {border: solid 1px #000; margin:5px;}
.extra {border:0px !important;}
.single {margin-left:10px !important; border:0px !important;}
span.single {display:inline-block; margin-left:20px;}
</style>
Use this to call your Function
<div class="parent"><? RecursiveWrite($role, $child);?></div>
Put all the code Provided in one page with your array.
For better Codding standard you should Septate your style html and php for this try your luck ;)
You're not closing the div in the right places, when calling the recursion, right after ending the recursion you need to write the ending div:
open div
run recursion
close div
As well, you have two unnecessary div closing. Always make sure you open as many div as you close and vice versa. I've marked the places that needed to be changed in the code.
code:
<?php
$child = 0;
function RecursiveWrite($array, $child ) {
$parent_array_size = count($array);
foreach ($array as $key => $vals) {
if(is_array($vals)){
$inner_array_size = count($vals);
echo "<div class='main clear'><input type='checkbox'/> ".$key." ";
RecursiveWrite($vals,$child);
echo "</div>"; /* <== ADD THIS */
}else{
$child = 0;
if(is_numeric($key)){
echo " <div class='left'> <input type='checkbox' class=''/> ".$vals." </div>"; /* <== REMOVE EXTRA DIV */
}else{
echo "<div class='clear'><input type='checkbox'/> ".$key." </div>"; /* <== REMOVE EXTRA DIV */
}
}
//
}
}
RecursiveWrite($role, $child);
?>
you can find a working example at http://codepad.viper-7.com/507rLc
I've 2 tables named preacher & Sermons
Fields of Preacher
preacher_id
first_name
last_name
preacher_image
preacher_logo
preacher_bio_brief
category
fields of sermons
sermon_id
preacher_id
sermon_title
sermon_image
audio_file
sermon_description
sort_order
I want to display all the sermons of each preacher by the order of preacher first_name.I got it properly but also got the below error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: 1
Filename: home/sermons_view.php
Line Number: 27
method in controller
function index() {
$res = $this->sermon_model->viewAllpreachers();
$this->data['preachers'] = $res;
$this->data['page'] = $this->config->item('APP_template_dir') . 'site/home/ sermons_view';
$this->load->vars($this->data);
$this->load->view($this->_container);
}
Method in model
function viewAllpreachers() {
$preacher = array();
$this->db->select('*');
$this->db->from('preacher');
$this->db->order_by('first_name');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$preacher[$row->preacher_id]['preacher_id'] = $row->preacher_id;
$preacher[$row->preacher_id]['preacher_name'] = $row->first_name . ' ' . $row->last_name;
$preacher[$row->preacher_id]['preacher_image'] = $row->preacher_image;
$preacher[$row->preacher_id]['preacher_bio_brief'] = $row->preacher_bio_brief;
$this->db->select('*');
$this->db->from('sermons');
$this->db->where('preacher_id',$row->preacher_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row1) {
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_id'] = $row1->sermon_id;
$preacher[$row1->preacher_id][$row1->sermon_id]['preacher_id'] = $row1->preacher_id;
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_image'] = $row1->sermon_image;
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_title'] = $row1->sermon_title;
$preacher[$row1->preacher_id][$row1->sermon_id]['audio_file'] = $row1->audio_file;
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_description'] = $row1->sermon_description;
}
}
}
return $preacher;
}
return false;
}
code in View
<?php
if ($preachers) {
foreach ($preachers as $val) {
?>
<tr>
<td><img src="<?= base_url(); ?>uploads/<?= $val['preacher_image']; ?>"/></td>
<td colspan="2"><?= $val['preacher_name']; ?></td>
<td colspan="2"><?= $val['preacher_bio_brief']; ?></td>
</tr>
<?
echo '<pre>';
//print_r($val);
echo '</pre>';
foreach ($val as $val1) {
?>
<tr>
<td style="padding-left: 50px; "><img src="<?= base_url(); ?>uploads/<?= $val1['sermon_image']; ?>" style="width: 60px;height: 60px;"/></td>
<td><?= $val1['sermon_title']; ?></td>
<td><?= $val1['audio_file']; ?></td>
<td width="250px"><?php $res = explode('/', $val1['audio_file']);
if ($val1['audio_file']) {
?><a id="play" href="<?= site_url('sermons/playmp3/' . $val1['sermon_id']); ?>"><?= $res['1']; ?></a><?php } ?></td>
<td><?= $val1['audio_file']; ?></td>
</tr>
<?
}
}
}
?>
I think its the problem with the resultant array
I got that like
Array
(
[21] => Array
(
[preacher_id] => 21
[preacher_name] => Vance Havner
[preacher_image] => profile_image/havner.jpeg
[preacher_bio_brief] => this is for testing
[42] => Array
(
[sermon_id] => 42
[preacher_id] => 21
[sermon_image] => sermon_image/image_81322797345.jpg
[sermon_title] => 3 notes of the devil's tales
[audio_file] => audio_file/Niranja_Mizhiyum1.mp3
[sermon_description] => 3 notes of the devil's tales
)
[41] => Array
(
[sermon_id] => 41
[preacher_id] => 21
[sermon_image] =>
[sermon_title] => The Lordship of Christs
[audio_file] => audio_file/Naladhamayanthi_Kadhayile.mp3
[sermon_description] => the lordship of christ
)
)
)
there is no $res in your model
first debug what is $res with print_r($res) and
AFAIK there must be $val1['sermon_title'] instead of $res['1']
My problem is, I key in the sibling details in the first row textboxs and i select the check box no error display. If i didn't select the checkbox its display the below error. Can you give some idea? i am new for CodeIgniter.
I got error message: (How i can solve the error)
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: controllers/registration.php
Line Number: 288
Below my Code:
foreach($querystud_frm->result() as $row)
{
echo "<tr><td>".$i.")</td>";
$data=array('name'=>'s_sibling_name[]','class'=>'textbox','value'=>$row->s_sibling_name,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_nric[]','class'=>'textbox','value'=>$row->s_sibling_nric,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$sib_dob=date('d-m-Y',strtotime(trim($row->s_sibling_dob)));
$data=array('name'=>'s_sibling_dob[]','class'=>'textbox','value'=>$sib_dob,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_relation[]','class'=>'textbox','value'=>$row->s_sibling_relation,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_occupation[]','class'=>'textbox','value'=>$row->s_sibling_occupation,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_income[]','class'=>'textbox','value'=>$row->s_sibling_income,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$sib_yes = $row->s_sibling_yes;
echo $sib_yes;
if($sib_yes == 'YES')
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => TRUE);
echo "<td >".form_checkbox($data)."</td>";
}
else
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'NO', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
}
echo "</tr>";
$i++;
}
if($i<10)
{
$var=array("s_sibling_name","s_sibling_nric","s_sibling_dob","s_sibling_relation","s_sibling_occupation","s_sibling_income");
for($j=$i;$j<=10;$j++)
{
echo "<tr><td>".$j.")</td>";
foreach($var as $value)
{
$value=$value.'[]';
$data_val=array('name'=>$value,'class'=>'textbox','value'=>'','style'=>'text-transform:uppercase;');
echo "<td>".form_input($data_val)."</td>";
}
if($sib_yes == 'YES')
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => TRUE);
echo "<td >".form_checkbox($data)."</td>";
}
else
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'NO', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
}
echo "</tr>";
}
unset($var);
}
$querystud_frm->free_result();
}
else
{
$var=array("s_sibling_name","s_sibling_nric","s_sibling_dob","s_sibling_relation","s_sibling_occupation","s_sibling_income");
$var_sib=array("s_sibling_yes");
for($i=1;$i<=10;$i++)
{
echo "<tr><td>".$i.")</td>";
foreach($var as $value)
{
$name=$value.'[]';
$data=array('name'=>$name,'class'=>'textbox','value'=>'','style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
}
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
echo "</tr>";
}
unset($var,$i,$data,$var_sib);
}
controller/registration.php
if($this->input->post('siblingsfrm'))
{
$this->data['nric']=$this->input->post('s_nric');
//echo $this->input->post('name');
$name=$this->input->post('s_sibling_name');
$nric=$this->input->post('s_sibling_nric');
$dob=$this->input->post('s_sibling_dob');
//$dob=strtotime($dob);
//$dob=date('Y-m-d',strtotime($dob));
$relation=$this->input->post('s_sibling_relation');
$occupation=$this->input->post('s_sibling_occupation');
$income=$this->input->post('s_sibling_income');
$sib_yes=$this->input->post('s_sibling_yes');
$sib_id=$this->input->post('s_sibling_id');
//print_r($sib_id);
//print_r($name);
//exit();
//$this->load->helper('date');
for($i=0;$i<count($name);$i++)
{
if($name[$i]!='')
{
$income[$i]=trim($income[$i]);
if($income[$i]=='')
$income[$i]=0;
if($sib_yes[$i]!= 'YES')
$sib_yes[$i]='NO';
$date=date('Y-m-d',strtotime(trim($dob[$i])));
$insert_values=array('s_nric'=>$this->data['nric'],'s_sibling_name'=>strtoupper(trim($name[$i])),
's_sibling_nric'=>strtoupper(trim($nric[$i])),'s_sibling_dob'=>$date,
's_sibling_relation'=>strtoupper(trim($relation[$i])),
's_sibling_occupation'=>strtoupper(trim($occupation[$i])),
's_sibling_income'=>strtoupper(trim($income[$i])),
's_sibling_yes'=>trim($sib_yes[$i]));
if(is_array($sib_id) && isset($sib_id[$i]) )
{
$where=array('s_sibling_id'=>$sib_id[$i]);
$this->db->update('si_student_siblings',$insert_values,$where);
}
else
{
//print_r($insert_values);
$this->db->insert('si_student_siblings',$insert_values);
}
}
}
$this->data['level']=7;
}
The problem is that if a checkbox wasn't checked, it won't send any data at all to the server. So, this line of code...
$name=$this->input->post('s_sibling_name');
...will actually set the $name variable to FALSE (see $this->input->post() documentation in the guide)
Thus, the first time through your loop, your code is looking for the array item at $name[0], when in fact $name is not even an array, it's FALSE.
You could surround your for loop with an if/else statement to solve this problem (not the most elegant solution, but it would work):
if (is_array($name) && count($name) > 0)
{
for($i=0;$i<count($name);$i++)
{
if($name[$i]!='')
//etcetera...
}
}