I have an array $category['transactions']. It stores data as follow:
ID Name Phone
1 Test Test2
2 Test3 Test4
It's because I use the same array for different purpose, at one of the scenario is to show only the first record in this array. I don't what to change the coding in php nor creating a different parameter. What can I improve based on the following coding in html to get the first record only in this array?
<?php foreach($category['transactions'] as $transaction) { ?>
<div><?php echo $transaction['id']; ?></div>
<div><?php echo $transaction['name']; ?></div>
<?php } ?>
replace your code with.
<?php $firstRow=reset($category['transactions']);
echo '<div>',$firstRow['id'],'</div>';
echo '<div>',$firstRow['name'],'</div>';
?>
You don't need to iterate through the array to get the first element.
You don't even need the foreach to get the first element. Just use array_values():
$first = array_values($category['transactions')[0]
try this..
<?php
foreach($category['transactions'] as $transaction)
{
echo $transaction['id'];
break;
}
?>
and no need to use multiple php tags...
Related
I'm trying to make a fun side project and have come to a stop on a small problem. I am trying to have the echo command placed inside of the while and mysqli_fetch_assoc command as the data changes everytime the page refreshes, from the select from table random function.
I select random items like this:
$survivor_set = random_survivor();
$item_set = random_item();
$firstaidkitaddon_set = random_firstaidkitaddon();
$flashlightaddon_set = random_flashlightaddon();
$keyaddon_set = random_keyaddon();
$mapaddon_set = random_mapaddon();
$toolboxaddon_set = random_toolboxaddon();
$survivoroffering_set = random_survivoroffering();
The problem line of code looks like this:
<?php while($toolboxaddon = mysqli_fetch_assoc($toolboxaddon_set)) { ?>
However I need the words after $ to be changed so was looking for something like this to work:
<?php while($ echo h($item['item']);addon = mysqli_fetch_assoc($ echo h($item['type']);addon_set)) { ?>
This is probably explained poorly, I would appreciate if anyone could lend some time to help me where I can show in more details what exactly I am trying to accomplish.
The code shows the random item that was selected from the table.
<?php while($item = mysqli_fetch_assoc($item_set)) { ?>
<?php echo h($item['name']);?> E.g. Engineers Toolbox
<?php echo h($item['rarity']);?> E.g. veryrare
<?php echo h($item['type']);?> E.g. toolbox
<?php echo h($item['media']);?> E.g. engineerstoolbox.png
<?php } ?>
I am then trying to find a way to put the echo h($item['type']) into the next output. so it would look like this when it is a toolbox.
<?php while($toolbox = mysqli_fetch_assoc($toolbox_set)) { ?>
But then could change due to it being a different item type that was pulled:
<?php while($flashlight = mysqli_fetch_assoc($flashlight_set)) { ?>
Full code, for context: https://zerobin.net/?9f772676aa87df3f#Gxy43WGqShTkL/VG42+t3nT4+sxGhxFy+GDB0B3+YH0=
You should store all your different add-on results in an associative array where the keys match the possible "type" values from your main item query. This allows you to select an item from the array using a string to reference its key - and you can take that string value from your $item['type'] variable.
e.g.
$survivor_set = random_survivor();
$item_set = random_item();
$addons = array(
"firstaid" => random_firstaidkitaddon(),
"flashlight" => = random_flashlightaddon(),
"key" = random_keyaddon(),
"map" = random_mapaddon(),
"toolbox" => random_toolboxaddon()
);
$survivoroffering_set = random_survivoroffering();
Then later on you can select the right set of results from the associative array by selecting the index which matches $item['type']:
<div class="itemaddonscontainer">
<div class="<?php echo h($item['type']);?>">
<?php while($addon = mysqli_fetch_assoc($addons[$item['type']])) { ?>
<img class="<?php echo h($addon['rarity']);?> survivor-item" src="imgs/survivor/itemaddon/<?php echo h($addon['media']);?>"/>
<?php } ?>
</div>
</div>
N.B. mysqli_free_result probably isn't necessary here.
I'd like to have 2 foreach loops for 2 arrays like that, I know it's wrong:
$properties has 6 items and $set_properties has 11 items
<?php if(!empty($properties)) : foreach ($properties as $prop) : ?>
<?php if(!empty($set_properties)) : foreach ($set_properties as $set_prop) : ?>
<?php endforeach; endif; ?>
<?php endforeach; endif; ?>
What would be the right way, because right now I'm getting too many loops if I want to echo something out ($prop->ID).
My goal is to make dropdown selectors($properties) and have $set_properties as options.
Try the following snippet, which I commented to hopefully help you understand.
//check if properties is empty, if not, loop through them.
if(!empty($properties)):
foreach ($properties as $prop):
//check if $set_properties is empty, if not create select element
if(!empty($set_properties)):
//loop through properties, generate select element for current index
//obviously you can do proper select element naming and everything I just don't know your markup
//notice I do this after checking if the options fields are empty, so that way it only appears if there are options associated with it.
echo $prop->ID.": <select>";
//loop through set_properties, generate options
foreach ($set_properties as $set_prop):
echo "<option value='{$set_prop->ID}'>{$set_prop->Name}</option>";
endforeach;
//end select element, so next iteration will make a new one.
//again, inside the check for $set_properties because the select element will only exist if options exist
echo "</select>";
endif;
endforeach;
endif;
In your original code you switch in and out of PHP very often, and that is really not necessary, it makes the code look messy and it's harder to format. Just write it all in PHP as there isn't much HTML that goes into it. You should only switch in/out of PHP if you are only trying to insert a variable into an element, or if there is a lot of HTML.
I have the following piece of HTML in a PHP app with an array including Group and Items. First I want to sort them by Groups, then within Groups have Items separated by comma (Item1, Item2, Item3), without ending comma.
<dl>
<?php $groupname = '' ?>
<?php foreach ($product['product_filters'] as $product_filter) { ?>
<?php if ($groupname != $product_filter['group']) { ?>
<?php $groupname = $product_filter['group']; ?>
<?php echo '<dd>' . $product_filter['group'] . '</dd>'; ?>
<?php } ?>
<dt>
<?php echo $product_filter['name']; ?>
</dt>
<?php } ?>
</dl>
I want to have a the following result, but I don't know how to manage it and which loop should I use:
Group 1
G1_Item_1, G1_Item_2
Group 2
G2_Item_1, G2_Item_2, G2_Item_3
You could use two loops: one to restructure your data into groups, and one just for outputting it in the desired format. Note that you used <dt> and <dd> in the opposite sense: the groups are the titles, so use <dt> for them.
Also, your code becomes much more readable if you don't open and close the php tag on every line. Try to make code blocks that don't have such interruption: it will make it so more readable.
Here is the suggested code:
<?php
// Create a new structure ($groups): one entry per group, keyed by group name
// with as value the array of names:
foreach ($product['product_filters'] as $product_filter) {
$groups[$product_filter['group']][] = $product_filter['name'];
}
// Sort it by group name (the key)
ksort($groups);
// Print the new structure, using implode to comma-separate the names
foreach ($groups as $group => $names) {
echo "<dt>$group</dt><dd>" . implode(', ', $names) . "</dd>";
}
?>
See it run on eval.in.
I have this piece of code in one single file
//declaring something
$array=array();
$arraylst=/*retrieve from database query and sure this contains the correct result*/
<?php
if(!empty($array)):
?>
<div id="something">
<?php
$n=0;
foreach($arraylst as $key=>$val):
$array="span".$n;
//create a span and print out $val's property1
$n++;
endforeach;
$n=0;
foreach($array as $key=>$val):
//create a span and print out $val's property2
$n++;
endforeach;
</div>
<?php
endif;
?>
<script language="javascript">
var arr=[<?php echo json_encode($array); ?>]
//do something else
</script>
The output to the screen I see is only one "span"; that is if my arraylst size is 3, I can only see the first span because my database query is sorted ascendingly. The rest is not seen at all.
$array="span".$n; overwrites the array with a string.
Use array_push( $array, "span$n" ); to add an item to the array.
(Then you'll want to remove the [ and ] from around the json_encode as you'll have an array in $array).
You always set the value "span" to $array.
$array="span".$n;
You do not add it to the array you set the array to that value.
Use:
$array[] ="span".$n;
The code loop an array and display all views for a user. Now things changed and I just need to display one result from a foreach loop. How do I do that?
<table class="report_edits_table">
<thead>
<tr class="dates_row">
<?php foreach($report['edits'] as $report_edit) : ?>
<td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container">
<?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?>
<span class="ui-icon ui-icon-trash">Remove</span>
<?php endif?>
<?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach($report['edits_titles'] as $index => $title) : ?>
<tr class="coach_row">
<?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?>
<td class="name_column"><?php echo $title ?></td>
<td class="value_column"><?php echo $report_edit[$index] ?></td>
<?php endfor ?>
</tr>
<?php endforeach ?>
</tbody>
Use the break command for simple conversion:
<?php for ... ?>
... stuff here ...
<?php break; ?>
<?php endfor ... ?>
A better solution would be to remove the foreach completely.
It sounds like you want to grab the first element from an array without having to loop through the rest of them.
PHP provides a set of functions for situations like this.
To get the first element in an array, start off using the reset() function to position the array pointer to the start of the array, then use the current() function to read the element that the pointer is looking at.
So your code would look like this:
<?php
reset($report['edits']);
$report_edit = current($report['edits']);
?>
Now you can work with $report_edits without having to use a foreach() loop.
(note that the array pointer does actually start by default at the first record, so you could skip the reset() call, but it's best practice not to do that because it might have been changed elsewhere in your code without you realising it)
If you want to move on to the next record after that, you can use the next() function. As you can see, if you wanted to, it would theoretically be possible to use these functions to write an alternative type of foreach() loop. There wouldn't be any point in using them them that way, but it's possible. But they do allow more fine-grained control over the array, which is handy for situations like yours.
Hope that helps.
Plenty of ways
Access the index of the array element in question directly
Update whatever logic fetches/generates the array to only return the element of interest
Use a for loop that terminates after a single loop
array_filter your array to get the element of interest
Break at the end of your foreach loop so it terminates after the first iteration
Conditionally check your index in the foreach loop and only output markup if the index matches the element of interest
And so on
I'd recommend just getting the array element of interest (number 2 on the list) as it means less data bouncing around your code (and probably between your PHP box and the database if you're populating the array from an SQL server)
Simplest method?
Place a break as the last line of your foreach. It'll execute once, then quit. (As long as which element you stop on is of no importance).
Secondary method: use array_pop or array_shift on your $report['edits'] or $report['edits_titles'] to get on element, lose the for loop, and reference the element you just retrieved.
For example:
//
// current
//
foreach ($report['edits'] as $report_edit) :
/* markup */
endforeach;
//
// modified version
//
$report_edit = array_shift($report['edits']);
/* markup */
Use <?php break ?> before <?php endforeach ?>
example ::
<?php
foreach ($this->oFuelData AS $aFuelData ) {
echo $aFuelData['vehicle'];
break;
}
?>
You can also use it for reference
foreach($array as $element) {
if ($element === reset($array))
echo $element;
if ($element === end($array))
echo $element;
}