How to display comma in PHP array? - php

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
}
}
}

Related

adding attributes Html::img yii2

I add images to the page, to which I add some attributes
<?php
$data = [
[
'data-z-index' => 1,
'data-width' => 300,
]
];
?>
<?php foreach ($posts as $i => $item) { ?>
<div class="item">
<?php if ($item->img) { ?>
<?= Html::img($item->img->getUrl(), $data[$i]) ?>
<?php } ?>
</div>
<?php } ?>
As a result, on the page all this works for me and I get
<img src="//test.loc/storage/posts-image/1-2.jpg" alt="" data-z-index="1" data-width="300">
Now I also want to add an alt attribute that will come from the database
<?= Html::img($item->img->getUrl(), [$data[$i], 'alt' => $item->img_alt]) ?>
But now the attribute formatting is changing and 0 appears at the beginning
<img src="//test.loc/storage/posts-image/1-2.jpg" alt="post1" 0-data-z-index="1" 0-data-width="300">
What could be the problem?
It's because $data is an array. So you have a nested array as options.
Try to merge the arrays:
array_merge($data[$i], ['alt' => $item->img_alt]);

targeting nested foreach loop array in php

I want to foreach loop through the $tabs['downloads'] subarray element (see bottom of following snippet) within the parent foreach $content['tabs'] loop. My attempt is not working. I get an Invalid argument. Suggestions are appreciated.
Sample of $content array:
$content=
[tabs' => [
0 => [
'label' => 'Afoxé',
'downloads' => [
0 => 'afoxe2.mscz',
1 => 'afoxe2.pdf'],
'content' => "blah blah",
],
]
Nested foreach loop:
<? $i = 1; foreach($content['tabs'] as $key => $tab):
$tabid=$tab['label'] . "-" . $tabsuffix; ?>
<div class="tab-pane fade <?= ($i == 1 ? "show active" : "")?>" id="pills-<?=$tabid?>" role="tabpanel"
aria-labelledby="pills-<?=$tabid?>-tab" tabindex="0">
<?= $Parsedown->text($tab["content"]) ?>
<? foreach($tab['downloads'] as $download): ?>
<a class="btn btn-orange blob text-white" role="button" href="../public/<?= $download ?>"
download="<?= $download ?>"><?= $download ?></a>
<? endforeach; ?>
</div>
<? $i++; endforeach; ?>
The only undefined index I see in your code is the video field.
That is easily fixable with the use of the Null Coalescing Operator. This only works with PHP 7+ What it does is return its first operand if it exists and is not null; otherwise it returns its second operand.
As an alternative you can always use if(isset($tab['video'])) before using the tested key anywhere else.
There is also the $tabsuffix but I will assume that is defined before the foreach.
However, if, for example, not all your entries have the downloads key, you should also handle that:
<? $i = 1;
foreach($content['tabs'] as $key => $tab):
$tabid=$tab['label'] . "-" . $tabsuffix; ?>
<div class="tab-pane fade <?= ($i == 1 ? "show active" : "")?>" id="pills-<?=$tabid?>" role="tabpanel"
aria-labelledby="pills-<?=$tabid?>-tab" tabindex="0">
<? if( stripos(str_replace(' ', '', $tab['video'] ?? ''), '</iframe>' ) !== false ) : // <--- check this line ?>
<div class="ratio ratio-16x9">
<?= $tab["video"] ?>
</div>
<? endif; ?>
<?= $Parsedown->text($tab["content"]) ?>
<? foreach($tab['downloads'] ?? [] as $download): // <--- and this line ?>
<a class="btn btn-orange blob text-white" role="button" href="../public/<?= $download ?>"
download="<?= $download ?>"><?= $download ?></a>
<? endforeach; ?>
</div>
<? $i++; endforeach; ?>
You can see this code working here. I have also added data with a video and one without the downloads key

PHP my code failed

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>

Compare and show different data from two tables

I've got two tables. Skills, that contains all the available skills.
and user_skills, that contains which skills user got.
I need to output all the available skills, and those skills that the user have (I select it by session['username']) will be marked (checked checkbox).
$get_all_skills = mysqli_query($conn, "SELECT * FROM skills");
$web_design = array();
$web_develop = array();
$automation = array();
$security = array();
while($show_row = mysqli_fetch_array($get_all_skills)){
switch($show_row['skill_type']){
case '1':
array_push($web_design, $show_row['skill_name']);
break;
case '4':
array_push($web_develop, $show_row['skill_name']);
break;
case '3':
array_push($automation, $show_row['skill_name']);
break;
case '2':
array_push($security, $show_row['skill_name']);
break;
}
}
How can possibly I make this work?
Part of the html is:
<div class="">
<ul class="to_do">
<?php
for($i=0;$i<count($web_develop);$i++){
?>
<li>
<p>
<input type="checkbox" class="flat"> <?php echo $web_develop[$i];?> </p>
</li>
<?php } ?>
</ul>
</div>
Considering you have a user_skills array ($user_skills_array) declared and have the data, use the below html code
<div class="">
<ul class="to_do">
<?php
for($i=0;$i<count($web_develop);$i++){
// check the global skill is available in the user skill set
$checked = (in_array($web_develop[$i], $user_skills_array)) ? 'checked="checked"': '';
?>
<li>
<p>
<input type="checkbox" class="flat" <?php echo $checked;?>> <?php echo $web_develop[$i];?> </p>
</li>
<?php } ?>
</ul>
</div>
try the following, explanation below.
<?php
$get_all_skills = mysqli_query($conn, "SELECT * FROM skills");
$availableSkills = [];
$skillTypes = [
1 => 'Webdesign',
2 => 'Security',
3 => 'Automation',
4 => 'Web Development',
];
while($show_row = mysqli_fetch_array($get_all_skills)){
$skill = [
'id' => $show_row['id'];
'name' => $show_row['name'];
];
$skillType = $show_row['skill_type'];
$availableSkills[$skillType][] = $skill;
}
// assuming user_skills:
$userSkills = [
1,
2,
5,
8
];
?>
<ul class="to_do">
<?php foreach ($availableSkills as $type => $skillsForType) : ?>
<li>
<?= $skillTypes[$type] ?>
<ul>
<?php foreach ($skillsForType as $skill) : ?>
<li>
<input
type="checkbox"
class="flat"
name="skill[<?= $type ?>]"
value="<?= $skill['id'] ?>"
<?= in_array($skill['id'], $userSkills) ? 'checked="checked"' : ''
> <?= $skill['name'] ?>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul>
First you gather all skills, as have you already done.
Next I optimized your different skills array into one and listed all skill types.
The available skills are indexed by their type id (see $skillTypes).
Next I assumed your user-skill collection could be like shown.
In the HTML section I am iterating over every skill type and in a nested foreach echo all corresponding skills.
If the skill id of the current iteration is in_array of the user-skill-relation the "checked" attribute is set.
To clarify I used short syntax in this example.
[] --> array()
<?= --> <?php echo
foreach () : endforeach;

List to DropDown list in Yii

Please help with this code:
<ul class="activity-projects">
<?php foreach ($ownProjects as $userProject) : ?>
<li>
<a class="<?php echo ($userProject->id == $project_id) ? 'active' : '';?>"
href="<?php echo Yii::app()->createUrl('user/activity', array(
'user_id'=>$user->id,
'project_id'=>$userProject->id,
'date'=>$date)
); ?>"><?php echo $userProject->name; ?></a>
</li>
<?php endforeach; ?>
<?php foreach ($projects as $userProject) : ?>
<li>
<a class="<?php echo ($userProject->project_id == $project_id) ? 'active' : '';?>"
href="<?php echo Yii::app()->createUrl('user/activity', array(
'user_id'=>$user->id,
'project_id'=>$userProject->project->id,
'date'=>$date)
); ?>"><?php echo $userProject->project->name; ?></a>
</li>
<?php endforeach; ?>
</ul>
How to change it to dropdown list, using CHtml::dropDownList. Thanks for watching!
First, you need to define a key-value array like this:
$options = array();
<?php foreach ($ownProjects as $userProject)
array_push($options, array($userProject->id => $userProject->name));
?>
echo CHtml::dropDownList('seletName', '1', $options);
This will be produced an html <select> tag with "seletcName" name. And also option with value "1" will be selected option. You can use your desired value for first and second parameters.
Also you can use CActiveForm#dropDownList for this purpose.
In your form, use the form dropDownList() function.
<?php echo $form->dropDownList(
$model,
'project_id',
CHtml::listData(OwnProjects::model()->findAll(),
'id', 'name'),
array('empty' => '(Select project)','class'=>"form-control")
);
?>
From your example, it looks like OwnProjects is not a model on its own, but a subset of a model. You can customise the query
<?php echo $form->dropDownList(
$model,
'project_id',
CHtml::listData(OwnProjects::model()->findAllByAttributes(array('user_id'=> Yii:app()->user->id),
'id', 'name'),
array('empty' => '(Select project)','class'=>"form-control")
);
?>
This solution finally helps me:
<?php $options = array();
foreach ($projects as $userProject) :
$options[$userProject->id] = $userProject->project->name;
endforeach;
echo CHtml::dropDownList('selectName', '1', $options);
?>

Categories