PHP my code failed - php

am i an idiot. 2 hours on something that seems to be simple and i don't get it.
I have an array like that:
Date | Surname
10/06/2016 Alex
10/06/2016 Marc
12/06/2016 John
12/06/2016 Steve
13/06/2016 Elliot
What i want is:
<div>
<div><h4>10/06/2016</h4></div>
<ul>
<li>Alex</li><li>Marc</li>
</ul>
</div>
<div>
<div><h4>12/06/2016</h4></div>
<ul>
<li>John</li><li>Steve</li>
</ul>
</div>
<div>
<div><h4>13/06/2016</h4></div>
<ul>
<li>Elliot</li>
</ul>
</div>
Here my failed code:
<?php
$dateShareHistoric = '';
$createShareHistoric = false;
foreach ($listFileShareHistoric as $tFilesShareHistoric) {
if($dateShareHistoric == $tFilesShareHistoric['dateShare'])
{
?>
<li rel="<?php echo $tFilesShareHistoric['idFiles']; ?>" data-uniqueid="<?php echo $tFilesShareHistoric['uniqueid']; ?>"><?php echo $tFilesShareHistoric['dateShare'] .' :: '. $tFilesShareHistoric['nomDonne']; ?></li>
<?php
}
else if($createShareHistoric){
$createShareHistoric = false;
?>
</ul></p></div>
<div class="callout callout-info"><h4><?php echo $tFilesShareHistoric['dateShare']; ?></h4><p><ul>
<li rel="<?php echo $tFilesShareHistoric['idFiles']; ?>" data-uniqueid="<?php echo $tFilesShareHistoric['uniqueid']; ?>"><?php echo $tFilesShareHistoric['dateShare'] .' :: '. $tFilesShareHistoric['nomDonne']; ?></li>
<?php
}
else{
$createShareHistoric = true;
?>
<div class="callout callout-info"><h4><?php echo $tFilesShareHistoric['dateShare']; ?></h4><p><ul>
<li rel="<?php echo $tFilesShareHistoric['idFiles']; ?>" data-uniqueid="<?php echo $tFilesShareHistoric['uniqueid']; ?>"><?php echo $tFilesShareHistoric['dateShare'] .' :: '. $tFilesShareHistoric['nomDonne']; ?></li>
<?php
}
$dateShareHistoric = $tFilesShareHistoric['dateShare'];
}
I feel ashamed to ask for that, sorry. If needed, i can post a picture of what it give to me. But it's logic, div, contain other div and other div...

Based on your php and output image I'm guessing that your array looks like this:
$data = [
[
'dateShare' => '10/06/2016',
'nomDonne' => 'Alex'
],
[
'dateShare' => '10/06/2016',
'nomDonne' => 'Marc'
],
[
'dateShare' => '12/06/2016',
'nomDonne' => 'John'
],
[
'dateShare' => '12/06/2016',
'nomDonne' => 'Steve'
],
[
'dateShare' => '13/06/2016',
'nomDonne' => 'Elliot'
]
];
In my opinion it would be best to transform given array and group items by dateShare which should make the rest easier
$groupedByDate = [];
foreach ($data as $item) {
$groupedByDate[$item['dateShare']][] = $item;
}
Now we can iterate given array and build a html that you needed
$html = '';
foreach ($groupedByDate as $date => $items) {
$html .= "<div><div><h4>{$date}</h4></div><ul>";
foreach ($items as $item) {
$html .= "<li>{$item['nomDonne']}</li>";
}
$html .= "</ul></div>\n";
}
echo $html;
Note that it does a lot of string concatenation but the end result is what you wanted:
<div><div><h4>10/06/2016</h4></div><ul><li>Alex</li><li>Marc</li></ul></div>
<div><div><h4>12/06/2016</h4></div><ul><li>John</li><li>Steve</li></ul></div>
<div><div><h4>13/06/2016</h4></div><ul><li>Elliot</li></ul></div>

Related

Separately display Odd and Even array data in a foreach loop

<?php $ctr = 0; ?>
#foreach($level1['Weapons'] as $key => $header)
#if($ctr% == 0)
<div class="left">
#endif
#if($ctr% == 1)
<div class="right">
#endif
<ul>
<li>
<span class="ability">{{$key}}</span><br>
<p class="ability-desc">{{$header['desc']}}</p>
</li>
</ul>
#if($ctr == 8 || $ctr == 7)
</div>
#endif
<?php $ctr++; ?>
#endforeach
Array:
'level1' =>
array (
'Weapons' =>
array (
'Misfortune' =>
array (
'desc' => 'You can make any person fall',
),
'Sorrow' =>
array (
'desc' => 'You can make a person cry just by looking at them',
),
'Stink' =>
array (
'desc' => 'No living person can endure your fart',
),
'Harden' =>
array (
'desc' => 'You can make soft things hard, even water',
),
I have a foreach which will list all the item from the array description. My problem is I created an if statement to assign the values from ODD and EVEN array element to a div which will separate them into left and right according to result. I notice that the result only seems to display on the left side. How do I re-arrange or make an if statement that will satisfy my idea. I hope this question made sense.
I would build up 2 strings in your loop and then just echo them out after your loop. Been a while since I did php so there may be a few syntax errors but you should get the general idea:
<?php
$ctr = 0;
$leftLi = "";
$rightLi = "";
foreach($level1['Weapons'] as $key => $header)
{
if ($ctr % 2 == 0)
{
$leftLi += MakeLi($key, $header['desc']);
} else {
$rightLi += MakeLi($key, $header['desc']);
}
$ctr++;
}
function MakeLi($key, $headerText)
{
return "
<li>
<span class=\"ability\">" . $key . "</span><br>
<p class=\"ability-desc\">" . $headerText . "</p>
</li>";
}
?>
<div class="left">
<ul>
<?php echo $leftLi; ?>
</ul>
</div>
<div class="right">
<ul>
<?php echo $rightLi; ?>
</ul>
</div>

How to display comma in PHP array?

I am setting this array, and for the most part it works properly in my site. NOTE: This is a Joomla site and a VirtueMart PHP file for the email that the customer receives when ordering a product.
$addressBTOrder = array('email{br}', 'company{br}', 'title', 'first_name', 'last_name{br}', 'address_1{br}', 'address_2{br}', 'city', 'virtuemart_state_id', 'zip{br}', 'virtuemart_country_id{br}', 'phone_1{br}', 'phone_2{br}');
However, I need to add a comma (,) after CITY in the array to actually display a comma in the final output. If I just put the comma after city:
'city,'
... it does not work and the city output just doesn't display at all. I also tried the hex value for comma (%2c) but it didn't work either.
Here is the code that is creating the output:
<?php
foreach ($addressBTOrder as $fieldname) {
$fieldinfo = explode('{',$fieldname);
if (!empty($this->userfields['fields'][$fieldinfo[0]]['value'])) { ?>
<span class="values vm2<?php echo '-' . $this->userfields['fields'][$fieldinfo[0]]['name'] ?>" ><?php echo $this->escape($this->userfields['fields'][$fieldinfo[0]]['value']) ?></span> <?php
if (isset($fieldinfo[1]) && $fieldinfo[1] == 'br}') { ?>
<br class="clear" /> <?php
}
}
}
?>
What code do I need to put there to display a comma in the final output? For instance, I am making the line break work by using {br}. Thanks!
What I'm getting from your code is that you want to specify some sort of suffix after each output of the corresponding userfield value.
A differentapproach is to make use of your CSS classes. This means you can properly style your content without adding extra elements.
For example, going back to your original array without anything extra
$addressBTOrder = ['email', 'company', 'title', 'city', ...];
foreach ($addressBTOrder as $field) :
$userField = $this->userfields['fields'][$field];
if (!empty($userField['value'])) : ?>
<span class="values vm2-<?= $userField['name'] ?>">
<?= $this->escape($userField['value']) ?>
</span>
<?php endif; endforeach ?>
and, since you're already adding CSS classes which I'm guessing are like vm2-email, vm2-company, etc...
.vm2-email, .vm2-company {
display: block; /* same as adding a newline */
}
.vm2-city:after {
content: ",";
}
Original answer here...
I would recommend using a more succinct data format. For example
$br = '<br class="clear" />';
$addressBTOrder = [[
'key' => 'email',
'suffix' => $br
], [
'key' => 'company',
'suffix' => $br
], [
'key' => 'title',
'suffix' => ''
], /* etc */ [
'key' => 'city',
'suffix' => ','
]];
then you can iterate like this...
<?php foreach ($addressBTOrder as $field) :
$userField = $this->userfields['fields'][$field['key']];
if (!empty($userField['value'])) : ?>
<span class="values vm2-<?= $userField['name'] ?>">
<?= $this->escape($userField['value']), $field['suffix'] ?>
</span>
<?php endif; endforeach ?>
It's more clean and easy to design the view exactly you want instead of try to do this with code. For example something like this:
<?php if(!empty($this->userfields['fields']['email']['value'])): ?>
<span class="values vm2-email">
<?= $this->escape($this->userfields['fields']['email']['value']) ?></span>
</span>
<br class="clear" />
<?php endif; ?>
<?php if(!empty($this->userfields['fields']['city']['value'])): ?>
<span class="values vm2-city">
<?= $this->escape($this->userfields['fields']['city']['value']) ?>, </span>
</span>
<?php endif; ?>
<?php if(!empty($this->userfields['fields']['virtuemart_state_id']['value'])): ?>
<span class="values vm2-virtuemart_state_id">
<?= $this->escape($this->userfields['fields']['virtuemart_state_id']['value']) ?></span>
</span>
<?php endif; ?>
The problem is that you're expecting everything before { in the array element to be a key in the $this->userfields['fields'] array. But when you have a comma there, it doesn't match the array keys. So you need to remove the comma before using it as a key. And if it has a comma, you need to add that to the output.
foreach ($addressBTOrder as $fieldname) {
$fieldinfo = explode('{',$fieldname);
$name = $fieldinfo[0];
if ($name[-1] == ",") {
$comma = ",";
$name = substr($name, 0, -1);
} else {
$comma = "";
}
if (!empty($this->userfields['fields'][$name]['value'])) { ?>
<span class="values vm2<?php echo '-' . $this->userfields['fields'][$name]]['name'] ?>" ><?php echo $this->escape($this->userfields['fields'][$name]['value']) . $comma; ?></span> <?php
if (isset($fieldinfo[1]) && $fieldinfo[1] == 'br}') { ?>
<br class="clear" /> <?php
}
}
}

Foreach Nested Loops

So here is my code. The problem I am having is that I want the number from HP in my PHP code into my HP HTML code and the same thing with Cylinders. I have figured out the other stuff but when it comes to that part I am stuck
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$cars = array(
array(
"car" => "Ferrari",
"model" => "Testarossa",
"gearbox" => "Manual 5 Shift",
"designer" => "Battista Pininfarina",
"engine" =>
array(
"HP" => 390,
"Cylinders" => 12
),
),
);
?>
<?php foreach($cars as $cars_key => $car_val): ?>
<ul>
<div style="margin-bottom: 10px;">
<li><b>Car:</b> <?php echo $car_val["car"]; ?></li>
<li><b>Model:</b> <?php echo $car_val["model"]; ?></li>
<li><b>Gearbox:</b> <?php echo $car_val["gearbox"]; ?></li>
<li><b>Designer:</b> <?php echo $car_val["designer"]; ?></li>
<li><b>Engine</b></li>
<ul>
<li><b>HP:</b></li>
<li><b>Cylinders:</b></li>
</ul>
</div>
</ul>
<?php endforeach; ?>
I have a few concerns:
You lose the brilliance/utility of an associative array when you hardcode values into your script that you could otherwise just call from the array.
I don't like the look of the mid-list <div>. I can't think of any good reason to break up your unorder list flow with it.
I don't like the floating sub-list either. It logically belongs to Engine and good markup would dictate that the sub-list exist inside of its parent.
Here is what I would suggest considering my above points...
*Some Notes:
I'm not sure how you want to layout multiple lists as your array grows in size.
The echoing is just my personal preference. You can bounce in and out of php if you like.
ucfirst() allows you to avoid hardcoding the keys.
My snippet will make your task clean, DRY, and concise.
Code: (Demo)
$cars = array(
array(
"car" => "Ferrari",
"model" => "Testarossa",
"gearbox" => "Manual 5 Shift",
"designer" => "Battista Pininfarina",
"engine" => array(
"HP" => 390,
"Cylinders" => 12
)
)
);
foreach($cars as $details){
echo "<ul style=\"margin-bottom:10px;\">";
foreach($details as $key=>$item){
echo "<li><b>",ucfirst($key),":</b>";
if(!is_array($item)){
echo " $item</li>";
}else{
echo "<ul>";
foreach($item as $subkey=>$subval){
echo "<li><b>$subkey:</b> $subval</li>";
}
echo "</ul>";
echo "</li>";
}
}
echo "</ul>";
}
Source Code Output:
<ul style="margin-bottom:10px;">
<li><b>Car:</b> Ferrari</li>
<li><b>Model:</b> Testarossa</li>
<li><b>Gearbox:</b> Manual 5 Shift</li>
<li><b>Designer:</b> Battista Pininfarina</li>
<li><b>Engine:</b>
<ul>
<li><b>HP:</b> 390</li>
<li><b>Cylinders:</b> 12</li>
</ul>
</li>
</ul>
Rendered Output: (run my snippet # phptester.net to see this)
From you example, it seems to me that the list is static and consists of two elements, then you need not use forEach at all.
<?php foreach($cars as $cars_key => $car_val): ?>
<ul>
<div style="margin-bottom: 10px;">
<li><b>Car:</b> <?php echo $car_val["car"]; ?></li>
<li><b>Model:</b> <?php echo $car_val["model"]; ?></li>
<li><b>Gearbox:</b> <?php echo $car_val["gearbox"]; ?></li>
<li><b>Designer:</b> <?php echo $car_val["designer"]; ?>
</li>
<li><b>Engine</b></li>
<ul>
<li><b>HP:</b><?php echo $car_val["engine"]["HP"]; ?></li>
<li><b>Cylinders:</b><?php echo $car_val["engine"]["Cylinders"]; ?></li>
</ul>
</div>
</ul>
<?php endforeach; ?>
If you do need to use a nested forEach, here is how you would go about doing that:
foreach($cars as $cars_key => $car_val):
if($cars_key == "engine")
foreach($car_val["engine"] as $engine_key => $engine_val):
echo $engine_key.$engine_val;
endforeach;
endforeach;

"Message: Undefined property: stdClass" codeigniter controller issue

First of all, I inherited the code for this site so I'm having trouble figuring out some of it. The problem is with our blog page creation. When I try to create a new blog page (using an admin site) I get an error before each element. It only appears on the create side and works fine on the edit side. I'm also still able to create the new post, it just has the notices. It was working as of about 24 hours ago and nothing was changed in any of the code.
The errors I'm getting are :
> A PHP Error was encountered
>Severity: Notice
>Message: Undefined property: stdClass::$keywords
>Filename: admin/form.php
>Line Number: 94
as well as:
> $title, Line Number: 28
> $comments_enabled, line 122
>$slug, line 33
>$status, line 38
>$body, line 53
>$preview_hash, line 58
I've narrowed it down to the $extra array code that doesn't seem to be getting read (maybe?). Here is my create function:
public function create()
{
// They are trying to put this live
if ($this->input->post('status') == 'live')
{
role_or_die('blog', 'put_live');
$hash = "";
}
else
{
$hash = $this->_preview_hash();
}
$post = new stdClass();
// Get the blog stream.
$this->load->driver('Streams');
$stream = $this->streams->streams->get_stream('blog', 'blogs');
$stream_fields = $this->streams_m->get_stream_fields($stream->id, $stream->stream_namespace);
// Get the validation for our custom blog fields.
$blog_validation = $this->streams->streams->validation_array($stream->stream_slug, $stream->stream_namespace, 'new');
// Combine our validation rules.
$rules = array_merge($this->validation_rules, $blog_validation);
// Set our validation rules
$this->form_validation->set_rules($rules);
if ($this->input->post('created_on'))
{
$created_on = strtotime(sprintf('%s %s:%s', $this->input->post('created_on'), $this->input->post('created_on_hour'), $this->input->post('created_on_minute')));
}
else
{
$created_on = now();
}
if ($this->form_validation->run())
{
// Insert a new blog entry.
// These are the values that we don't pass through streams processing.
$extra = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'category_id' => $this->input->post('category_id'),
'keywords' => Keywords::process($this->input->post('keywords')),
'body' => $this->input->post('body'),
'status' => $this->input->post('status'),
'created_on' => $created_on,
'created' => date('Y-m-d H:i:s', $created_on),
'comments_enabled' => $this->input->post('comments_enabled'),
'author_id' => $this->current_user->id,
'type' => $this->input->post('type'),
'parsed' => ($this->input->post('type') == 'markdown') ? parse_markdown($this->input->post('body')) : '',
'preview_hash' => $hash
);
if ($id = $this->streams->entries->insert_entry($_POST, 'blog', 'blogs', array('created'), $extra))
{
$this->pyrocache->delete_all('blog_m');
$this->session->set_flashdata('success', sprintf($this->lang->line('blog:post_add_success'), $this->input->post('title')));
// Blog article has been updated, may not be anything to do with publishing though
Events::trigger('post_created', $id);
// They are trying to put this live
if ($this->input->post('status') == 'live')
{
// Fire an event, we're posting a new blog!
Events::trigger('post_published', $id);
}
}
else
{
$this->session->set_flashdata('error', lang('blog:post_add_error'));
}
// Redirect back to the form or main page
($this->input->post('btnAction') == 'save_exit') ? redirect('admin/blog') : redirect('admin/blog/edit/'.$id);
}
else
{
// Go through all the known fields and get the post values
$post = new stdClass;
/*
---------Gives array to string error without the if statement-------
foreach ($this->validation_rules as $key => $field)
{
$post->$field['field'] = set_value($field['field']);
}*/
foreach ($this->validation_rules as $key => $field)
{
if (isset($_POST[$field['field']]))
{
$post->$field['field'] = set_value($field['field']);
}
}
$post->created_on = $created_on;
// if it's a fresh new article lets show them the advanced editor
$post->type or $post->type = 'wysiwyg-advanced';
}
// Set Values
$values = $this->fields->set_values($stream_fields, null, 'new');
// Run stream field events
$this->fields->run_field_events($stream_fields, array(), $values);
$this->template
->title($this->module_details['name'], lang('blog:create_title'))
->append_metadata($this->load->view('fragments/wysiwyg', array(), true))
->append_js('jquery/jquery.tagsinput.js')
->append_js('module::blog_form.js')
->append_js('module::blog_category_form.js')
->append_css('jquery/jquery.tagsinput.css')
->set('stream_fields', $this->streams->fields->get_stream_fields($stream->stream_slug, $stream->stream_namespace, $values))
->set('post', $post)
->build('admin/form');
}
The $extra array doesn't seem to be getting read. These errors also came about at the same time as an array to string error. I was hoping the fix for that would fix both but so far no good. The errors are coming from two sources as well. I was thinking it might be the if statement not being read? Or maybe it has something to do with the $validation_rules at the beginning of the file?
This bit of code is the first one to fail (for $type) and the only one through the actual controller.php file and the rest (keywords, title, slug, etc) fail under the form.php file.
$post->type or $post->type = 'wysiwyg-advanced';
Any advice or help is appreciated. I'm still fairly new to PHP and CodeIgniter but it looks like it'll be to much work to overhaul the website.
Thank you.
Edit: I've added my edit function below, maybe someone else can see why it works but not my create function.
public function edit($id = 0)
{
$id or redirect('admin/blog');
$post = $this->blog_m->get($id);
// They are trying to put this live
if ($post->status != 'live' and $this->input->post('status') == 'live')
{
role_or_die('blog', 'put_live');
}
// If we have keywords before the update, we'll want to remove them from keywords_applied
$old_keywords_hash = (trim($post->keywords) != '') ? $post->keywords : null;
$post->keywords = Keywords::get_string($post->keywords);
// If we have a useful date, use it
if ($this->input->post('created_on'))
{
$created_on = strtotime(sprintf('%s %s:%s', $this->input->post('created_on'), $this->input->post('created_on_hour'), $this->input->post('created_on_minute')));
}
else
{
$created_on = $post->created_on;
}
// Load up streams
$this->load->driver('Streams');
$stream = $this->streams->streams->get_stream('blog', 'blogs');
$stream_fields = $this->streams_m->get_stream_fields($stream->id, $stream->stream_namespace);
// Get the validation for our custom blog fields.
$blog_validation = $this->streams->streams->validation_array($stream->stream_slug, $stream->stream_namespace, 'new');
$blog_validation = array_merge($this->validation_rules, array(
'title' => array(
'field' => 'title',
'label' => 'lang:global:title',
'rules' => 'trim|htmlspecialchars|required|max_length[100]|callback__check_title['.$id.']'
),
'slug' => array(
'field' => 'slug',
'label' => 'lang:global:slug',
'rules' => 'trim|required|alpha_dot_dash|max_length[100]|callback__check_slug['.$id.']'
),
));
// Merge and set our validation rules
$this->form_validation->set_rules(array_merge($this->validation_rules, $blog_validation));
$hash = $this->input->post('preview_hash');
if ($this->input->post('status') == 'draft' and $this->input->post('preview_hash') == '')
{
$hash = $this->_preview_hash();
}
//it is going to be published we don't need the hash
elseif ($this->input->post('status') == 'live')
{
$hash = '';
}
if ($this->form_validation->run())
{
$author_id = empty($post->display_name) ? $this->current_user->id : $post->author_id;
$extra = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'category_id' => $this->input->post('category_id'),
'keywords' => Keywords::process($this->input->post('keywords'), $old_keywords_hash),
'body' => $this->input->post('body'),
'status' => $this->input->post('status'),
'created_on' => $created_on,
'updated_on' => $created_on,
'created' => date('Y-m-d H:i:s', $created_on),
'updated' => date('Y-m-d H:i:s', $created_on),
'comments_enabled' => $this->input->post('comments_enabled'),
'author_id' => $author_id,
'type' => $this->input->post('type'),
'parsed' => ($this->input->post('type') == 'markdown') ? parse_markdown($this->input->post('body')) : '',
'preview_hash' => $hash,
);
if ($this->streams->entries->update_entry($id, $_POST, 'blog', 'blogs', array('updated'), $extra))
{
$this->session->set_flashdata(array('success' => sprintf(lang('blog:edit_success'), $this->input->post('title'))));
// Blog article has been updated, may not be anything to do with publishing though
Events::trigger('post_updated', $id);
// They are trying to put this live
if ($post->status != 'live' and $this->input->post('status') == 'live')
{
// Fire an event, we're posting a new blog!
Events::trigger('post_published', $id);
}
}
else
{
$this->session->set_flashdata('error', lang('blog:edit_error'));
}
// Redirect back to the form or main page
($this->input->post('btnAction') == 'save_exit') ? redirect('admin/blog') : redirect('admin/blog/edit/'.$id);
}
// Go through all the known fields and get the post values
foreach ($this->validation_rules as $key => $field)
{
if (isset($_POST[$field['field']]))
{
$post->$field['field'] = set_value($field['field']);
}
}
$post->created_on = $created_on;
// Set Values
$values = $this->fields->set_values($stream_fields, $post, 'edit');
// Run stream field events
$this->fields->run_field_events($stream_fields, array(), $values);
$this->template
->title($this->module_details['name'], sprintf(lang('blog:edit_title'), $post->title))
->append_metadata($this->load->view('fragments/wysiwyg', array(), true))
->append_js('jquery/jquery.tagsinput.js')
->append_js('module::blog_form.js')
->set('stream_fields', $this->streams->fields->get_stream_fields($stream->stream_slug, $stream->stream_namespace, $values, $post->id))
->append_css('jquery/jquery.tagsinput.css')
->set('post', $post)
->build('admin/form');
}
Edit2: I've added the whole form.php that is sending most of the errors.
<section class="title">
<?php if ($this->method == 'create'): ?>
<h4><?php echo lang('blog:create_title') ?></h4>
<?php else: ?>
<h4><?php echo sprintf(lang('blog:edit_title'), $post->title) ?></h4>
<?php endif ?>
</section>
<section class="item">
<div class="content">
<?php echo form_open_multipart() ?>
<div class="tabs">
<ul class="tab-menu">
<li><span><?php echo lang('blog:content_label') ?></span></li>
<?php if ($stream_fields): ?><li><span><?php echo lang('global:custom_fields') ?></span></li><?php endif; ?>
<li><span><?php echo lang('blog:options_label') ?></span></li>
</ul>
<!-- Content tab -->
<div class="form_inputs" id="blog-content-tab">
<fieldset>
<ul>
<li>
<label for="title"><?php echo lang('global:title') ?> <span>*</span></label>
<div class="input"><?php echo form_input('title', htmlspecialchars_decode($post->title), 'maxlength="100" id="title"') ?></div>
</li>
<li>
<label for="slug"><?php echo lang('global:slug') ?> <span>*</span></label>
<div class="input"><?php echo form_input('slug', $post->slug, 'maxlength="100" class="width-20"') ?></div>
</li>
<li>
<label for="status"><?php echo lang('blog:status_label') ?></label>
<div class="input"><?php echo form_dropdown('status', array('draft' => lang('blog:draft_label'), 'live' => lang('blog:live_label')), $post->status) ?></div>
</li>
<li class="editor">
<label for="body"><?php echo lang('blog:content_label') ?> <span>*</span></label><br>
<div class="input small-side">
<?php echo form_dropdown('type', array(
'html' => 'html',
'markdown' => 'markdown',
'wysiwyg-simple' => 'wysiwyg-simple',
'wysiwyg-advanced' => 'wysiwyg-advanced',
), $post->type) ?>
</div>
<div class="edit-content">
<?php echo form_textarea(array('id' => 'body', 'name' => 'body', 'value' => $post->body, 'rows' => 30, 'class' => $post->type)) ?>
</div>
</li>
</ul>
<?php echo form_hidden('preview_hash', $post->preview_hash)?>
</fieldset>
</div>
<?php if ($stream_fields): ?>
<div class="form_inputs" id="blog-custom-fields">
<fieldset>
<ul>
<?php foreach ($stream_fields as $field) echo $this->load->view('admin/partials/streams/form_single_display', array('field' => $field), true) ?>
</ul>
</fieldset>
</div>
<?php endif; ?>
<!-- Options tab -->
<div class="form_inputs" id="blog-options-tab">
<fieldset>
<ul>
<li>
<label for="category_id"><?php echo lang('blog:category_label') ?></label>
<div class="input">
<?php echo form_dropdown('category_id', array(lang('blog:no_category_select_label')) + $categories, #$post->category_id) ?>
[ <?php echo anchor('admin/blog/categories/create', lang('blog:new_category_label'), 'target="_blank"') ?> ]
</div>
</li>
<?php if ( !module_enabled('keywords')): ?>
<?php echo form_hidden('keywords'); ?>
<?php else: ?>
<li>
<label for="keywords"><?php echo lang('global:keywords') ?></label>
<div class="input"><?php echo form_input('keywords', $post->keywords, 'id="keywords"') ?></div>
</li>
<?php endif; ?>
<li class="date-meta">
<label><?php echo lang('blog:date_label') ?></label>
<div class="input datetime_input">
<?php echo form_input('created_on', date('Y-m-d', $post->created_on), 'maxlength="10" id="datepicker" class="text width-20"') ?>
<?php echo form_dropdown('created_on_hour', $hours, date('H', $post->created_on)) ?> :
<?php echo form_dropdown('created_on_minute', $minutes, date('i', ltrim($post->created_on, '0'))) ?>
</div>
</li>
<?php if ( ! module_enabled('comments')): ?>
<?php echo form_hidden('comments_enabled', 'no'); ?>
<?php else: ?>
<li>
<label for="comments_enabled"><?php echo lang('blog:comments_enabled_label');?></label>
<div class="input">
<?php echo form_dropdown('comments_enabled', array(
'no' => lang('global:no'),
'1 day' => lang('global:duration:1-day'),
'1 week' => lang('global:duration:1-week'),
'2 weeks' => lang('global:duration:2-weeks'),
'1 month' => lang('global:duration:1-month'),
'3 months' => lang('global:duration:3-months'),
'always' => lang('global:duration:always'),
), $post->comments_enabled ? $post->comments_enabled : '3 months') ?>
</div>
</li>
<?php endif; ?>
</ul>
</fieldset>
</div>
</div>
<input type="hidden" name="row_edit_id" value="<?php if ($this->method != 'create'): echo $post->id; endif; ?>" />
<div class="buttons">
<?php $this->load->view('admin/partials/buttons', array('buttons' => array('save', 'save_exit', 'cancel'))) ?>
</div>
<?php echo form_close() ?>
</div>
</section>
In your code:
$post->type or $post->type = 'wysiwyg-advanced';
PHP will first evaluate $post->type, and if that returns false, the second part of your or statement will be run. Since PHP has to evaluate it, it will attempt to access the property, and since it's not set, the interpreter throws a notice and assumes it's false.
The proper way to do this is:
if (!isset($post->type)) {
$post->type = 'wysiwyg-advanced';
}
// Or in PHP 7:
$post->type = $post->type ?? 'nobody';
Replace
$post->type or $post->type = 'wysiwyg-advanced';
with
$post->type = 'wysiwyg-advanced';
hope it works..

Making a nested list with php foreach

I'm trying to make a nested list with php by using a foreach loop but I'm kind of stuck now. My code uses a foreach loop and checks if the item is a heading, if it is it will start a nested list below it. The problem now is that if it's not a heading I want to put the corresponding list items into a single ul element below its heading. Now as you can see it puts every single list items that isn't a heading into a seperate ul element of its own because of the foreach loop. How can I fix this?
<ul>
<?php foreach($listitems as $listitem) : ?>
<?php if( $listitem['heading'] == 1) : ?>
<li><?php echo $listitem['listitem']; ?><!--begin nested list-->
<?php endif; ?>
<?php if( $listitem['heading'] == 0) : ?>
<ul><li><?php echo $listitem['listitem']; ?></li></ul>
<?php endif; ?>
<?php endforeach; ?>
</li><!--end nested list-->
</ul>
This is the desired html output:
<ul>
<li>Javascript Basics<!--begin nested list-->
<ul>
<li>Getting Started</li>
<li>Data and Variables</li>
<li>Functions</li>
<li>Scope</li>
<li>Working With Objects</li>
<li>Creating Objects</li>
<li>Arrays</li>
<li>Conditions And Decisions</li>
<li>Loops</li>
</ul>
</li><!--end nested list-->
</ul>
You need to set the inner lists start and end tags when the heading changes.
Something like this
<ul>
<?php
$NonHeadCount = 0;
$HeadingOpen = false;
foreach($listitems as $listitem)
{
if( $listitem['heading'] == 1)
{
$HeadingOpen = true;
if ($NonHeadCount != 0)
{
echo "</ul>";
}
echo "<li>".$listitem['listitem'];
$NonHeadCount = 0;
}
if( $listitem['heading'] == 0)
{
if ($NonHeadCount == 0)
{
echo "<ul>";
}
echo "<li>".$listitem['listitem']."</li>";
}
}
if ($NonHeadCount != 0)
{
echo "</ul>";
}
if ($HeadingOpen)
{
echo "</li>";
}
?>
</ul>
You have to change the $listitems format.
Some like this:
<?php
$listitems = array(
'item1' => array(
'item11',
'item12',
'item13'
),
'item2' => array(
'item21',
'item22',
),
'item3',
'item4'
);
?>
Then, do this:
<?php
echo "<ul>";
foreach($listitems as $item => $listitem):
echo "<li>$item</li>";
if(count($listitem) > 0):
echo "<ul>";
foreach($lisitem as $item):
echo "<li>$item</li>";
endforeach;
echo "</ul>";
endif;
endforeach;
echo "<ul>";
?>

Categories