PHP post foreach value to seperate array - php

So...
I have this foreach loop with information about a product and I want to save the information to a seperate array for each loop.
I was thinking of doing something like this:
$return_array = array();
foreach($items as $item) {
$return_array[] = $item;
}
But I have troubles doing it like this since I am using input values from html and I need to add those before they get send to a database.
My foreach goes like:
foreach($items as $item) {
<table>
<tr>
<td>
<input value="<?= $item->name ?>" name="item<?= $item->id ?>">
</td>
</tr>
... more table tags
<?php foreach($item as $key) { ?>
<input name ="item<?= $item->id ?>_label<?= $key->label ?>
<?php } ?>
... more table tags
<select name="item<?= item->id ?>_status>
//Choose the state the product is in
<option value="damaged">
<option value="good">
</select>
So after this gets submitted with the form (this is in a btw) I get something like this:
(depending on how many labels the product has this number can increase)
$array =
['item1'] = 'test';
['item1_label1'] = 123;
['item1_label2'] = 213;
['item1_status'] = 'good';
['item2'] = 'test2';
['item2_label1'] = 112;
['item2_label2'] = 1232;
['item2_label3'] = 132;
['item2_status'] = 'broken';`
Now what I want would be:
$array =
['item1'] = array[ //name of this doesn't matter
['item1'] = 'test'; // name
['item1_label1'] = 123; //label
['item1_label2'] = 213; //label
['item1_status'] = 'good'; //status
],
['item2'] = array[
['item2'] = 'test2'; //name
['item2_label1'] = 112; //label
['item2_label2'] = 1232; //label
['item2_label3'] = 132; //label
['item2_status'] = 'broken' //status
]
];
I want to create this information from the form. (also the number of items can increase).

try this,
$result = [];
foreach($array as $k => $v)
{
//$result[substr($k, 0, 5)][$k] = $v;
if(strpos($k, '-') === FALSE)
$result[$k][$k] = $v;
else
$result[substr($k, 0, strpos($k, '-'))][$k] = $v;
}

Related

How to loop an exploded list of strings?

I have a list of country names in an input field like:
Spain Italy France Germany
So first of i make all the strings lowercase in order not to have a mismatch with the country name in the geoJson data. Then I compare the strings with the propriety name in the geoJson, and if it matches, i push it in the array.
$json = file_get_contents("../world_ita.json");
$data = json_decode($json, true);
$states = array();
$item = null;
$stateList = strtolower( usp_get_meta(false, 'usp-custom-3'));
$stateList = htmlspecialchars_decode ( $stateList);
$stateList = preg_replace("/\w[\w']*/e", "ucwords('\\0')", $stateList);
$stateList = explode(' ',$stateList);
foreach($data["features"] as $feature) {
$id = $feature["id"];
$name = $feature["properties"]["name"];
$feature["properties"]["density"] = 0;
foreach($stateList as $state) {
if ($name == $state) {
if (!in_array($name, $states)) {
$item = $feature;
array_push($states, $name);
}
} else { ?>
statesData.features.forEach(function(state) {
if ("<?php echo $id;?>" == state.id) {
state.properties.density += 10;
}
});
<?php }
}
}
if (!is_null($item)) : ?>
statesData.features.push(<?php echo json_encode($item); ?>);
<?php endif; ?>
The above is not working and it breaks it. I thought to first explode the strings and then loop them and run the other bits of the code, I am not sure where I am doing something wrong there.
UPDATE
What the above code does is to repeat the following for each single object in the geoJson
statesData.features.forEach(function(state) {
and it is not printing the coordinates as it should as I run the following by the end of it:
if (!is_null($item)) : ?>
statesData.features.push(<?php echo json_encode($item); ?>);
<?php endif;
It is only printing one single country coordinates but the name are the same as per the geoJson, so it should print all matching ones.
UPDATE 2
The code I am trying out is exactly this (different from the previous as per the new update):
var statesData = {
"type": "FeatureCollection",
"features": []
};
<?php
$json = file_get_contents("http://www.jikupin.com/world_ita.json");
$data = json_decode($json, true);
$states = array();
$classesForCountries = [];
$item = null;
$stateList = strtolower( usp_get_meta(false, 'usp-custom-3'));
$stateList = htmlspecialchars_decode ( $stateList);
$stateList = preg_replace("/\w[\w']*/e", "ucwords('\\0')", $stateList);
$stateList = explode(' ',$stateList);
foreach($data["features"] as $feature) {
$name = $feature["properties"]["name"];
foreach($stateList as $state) {
if ($name == $state) {
if (!in_array($name, $states)) {
$item = $feature;
array_push($states, $name);
}
}
}
}
if (!is_null($item)) : ?>
statesData.features.push(<?php echo json_encode($item); ?>);
<?php
endif;
?>
The above is not printing any coordinates, If I remove the explode and the loop I do for it, meaning if i run it for one single country, it works. When I run the explode and the loop for for that, and I try var_dumb($states), i get
value (0)

how to recieve auto generated array as post variable

I have tried this simple code to generate an array which will send and a form data in post method. what is the way of receiving this array in desired page? Here is the code:
$serial = 0;foreach ($results as $row) {$serial = $serial + 1;
Html:
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
$used_serials = $_POST['serials];
foreach( $used_serials AS &$serial ){
$key = 'question-'.$serial;
$wanted_serial_pack = $_POST[$key];
}
OR better use an multidimensional Array structure like:
name="question['serials'][$serial]"
Then you can loop over $_POST['serials]
PHP
$serial = 0;
$inputs = array();
foreach ($results as $row) {
$serial = $serial + 1;
$inputs[] = "<input name=\"question['keys']['{$serial}'][]\"/>";
}
template.php:
echo implode(' ',$inputs);
Submit.php
$results = $_POST['keys];
foreach($results as $serial_array){
var_dump($serial_array);
}
Something like this may help.

how to store values of foreach as array

<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);
foreach ($samgri as $row){
$puja_samagri = $row['puja_samagri'];
}
$puja_sam = explode(',', $puja_samagri);
foreach ($puja_sam as $samagri_id){
$samg = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}
if(sizeof($samg) == 0){
echo '<h5 style = "text-align:center">No samagari available</h5>';
}else{
foreach ($samg as $row){
?>
but it was fetching only the last record not total records
You should add brackets after the array name like:
<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);
//Declare the arrays
$puja_samagri = new array();
$samg = new array();
foreach ($samgri as $row){
$puja_samagri[] = $row['puja_samagri'];
}
$puja_sam = explode(',', $puja_samagri);
foreach ($puja_sam as $samagri_id){
$samg[] = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}
if(sizeof($samg) == 0){
echo '<h5 style = "text-align:center">No samagari available</h5>';
}else{
foreach ($samg as $row){
?>
It will use the automatic int position (from 0 going up untill you have all the results). Also it might be a good idea to declare them as arrays before using them.
You have to take array after every foreach veriable as like follows :
<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);
foreach ($samgri as $row){
$puja_samagri[] = $row['puja_samagri'];
}
$puja_sam = explode(',', $puja_samagri);
foreach ($puja_sam as $samagri_id){
$samg[] = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}
if(sizeof($samg) == 0){
echo '<h5 style = "text-align:center">No samagari available</h5>';
}else{
foreach ($samg as $row){
?>
Hope this will help you :)

dynamic variables from array

I store the field names within an array, in hopes to dynamically create the variables.
I receive a illegal offset type error for the if and else, these two lines:
$data[$tmp_field] = $tmp_field[$id];
$data[$tmp_field] = 0;
I checked the post data and it is posting with the appropriate data, but I am not sure what the problem is.
$student_id stores all the students ids., for example: $student_id = array(8,9,11,23,30,42,55);
function updateStudentInfo() {
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$tmp_field] = 0;
} else {
$data[$tmp_field] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
}
This is the array format I desire:
Array
(
[internet_student] => 1
[non_matriculated_student] => 1
[h_number] => 0
[felony] => 0
[probation] => 1
[dismissed] => 0
)
Added screenshot to give you a visual of the form the data is being posted from
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$field_name] = 0;
} else {
$data[$field_name] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
I am assuming that all these fields are arrays, as otherwise you wouldn't need any loops.
function updateStudentInfo()
{
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
$student_count = count($student_id);
foreach($student_id as $id)
{
$data = array();
foreach($fields as $field)
{
if(array_key_exists($id, $$field))
$data[$field] = ${$field}[$id];
}
}
}
You are trying to use the student id as an array key for the other fields but the HTML form is just a standard indexed array, not keyed to any student data.

Sorting text data by number value

I have mock fantasy football form that creates data in an external text file and I have everything working, I have just run into one problem. Can someone show me how I can sort the players by their number (largest on top) and then highlight (in red) the whole row of the player that has had the most points?
Here is my form file:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>Fantasy Football</title>
</head>
<body>
<form action="team.php" method="POST">
<table border="1">
<tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
<tr><td>Position</td><td><input type="text" name="position"</td></tr>
<tr><td>Number</td><td><input type="text" name="number"</td></tr>
<tr><td>Team</td><td><input type="text" name="team"</td></tr>
<tr><td>Points per game</td><td><input type="text" name="points"</td></tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
And here is the return data:
<?php
$name = $_POST['name'];
$team = $_POST['team'];
$number = $_POST['number'];
$position = $_POST['position'];
$points = $_POST['points'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../php/football.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
fwrite($fp, $name."|".$team."|".$number."|".$position."|".$points."\n");
?>
<?php
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$players = file("$DOC_ROOT/../php/football.txt");
echo "<table border='2'>";
echo "<tr> <td>Name</td> <td>Team</td> <td>number</td> <td>Position</td> <td>Points</td> </tr>";
for($i = 0; $i < sizeof($players); $i++) {
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
echo '<tr><td>'.$name.'</td><td>'.$team.'</td><td>'.$number.'</td>
<td>'.$position.'</td><td>'.$points.'</td></tr>';
}
echo '</table>';
?>
Not really good at inserting bits an pieces of code, so if you could, can you tell me exactly where to put whatever you can give me?
Update:
Is this where I needed to put everything? The way it is now, when I submit my form I don't see anything! Obviously I did something wrong, so I'm open to suggestions!
<?php
function sort_player_array( $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
?>
<?php
$name = $_POST['name'];
$team = $_POST['team'];
$number = $_POST['number'];
$position = $_POST['position'];
$points = $_POST['points'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../php/football.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
?>
<?php
fwrite($fp, $name."|".$team."|".$number."|".$position."|".$points."\n");
$players = file("$DOC_ROOT/../php/football.txt");
$player_array = array();
foreach($players AS $player)
{
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
$player_array[] = array('name' => $name,
'number' => $number,
'position' => $position,
'points' => $points,
);
}
$sorted_players = sort_player_array($player_array, 'number', true);
foreach( $sorted_players AS $player )
{
echo '<tr><td>'.$player[name].'</td><td>'.$player[team].'</td><td>'
.$player[number].'</td><td>'.$player[position].'</td><td>'.$player[points].'</td></tr>';
} ?>
first of all you are programming in PHP, use COUNT() instead of SIZEOF().
sizeof() is an alias of count() and might be removed as php evolves.
We need a function for sorting the array:
function sort_player_array( $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
next build an array with php holding your data, then sort it .
$players = file("$DOC_ROOT/../php/football.txt");
$player_array = array();
foreach($players AS $player)
{
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
$player_array[] = array('name' => $name,
'number' => $number,
'position' => $position,
'points' => $points,
);
}
We sort the array as you requested by number, but any key is possible. also you can set ASC or DESC with the third variable
$sorted_players = sort_player_array($player_array, 'number', true);
foreach( $sorted_players AS $player )
{
echo '<tr><td>'.$player[name].'</td><td>'.$player[team].'</td><td>'.$player[number].'</td><td>'.$player[position].'</td><td>'.$player[points].'</td></tr>';
}
Seems like you need some kind of sorting algorithm function for $players. There are different kinds, and you can find many by googling "sorting algorithms", or you can write one yourself if you feel like "reinventing the wheel". Doing one yourself does make for good practice/fun :D
Here's a link to a wiki on bubble sort, probably the most common basic sorting and would help in your situation.
Prepare an array $playerData, which contains all player records and use their numbers as key. Then use ksort():
ksort( $playerData );
While preparing the $playerData, keep a variable $maxPoints and $mapPointsPlayerNumber and check each player's data against these values. Update them if current player's point is higher than $maxPoints.
I think you should be able to create arrays with the list function. Something like this:
//set array variables
for($i = 0; $i < sizeof($players); $i++) {
list($name[],$team[],$number[],$position[],$points[]) = explode('|', $players[$i]);
}
//sort all arrays by the number, in descending order
array_multisort($number, $position, $name, $team, $points, SORT_DESC);
//set the highest points to mostPoints variable
var mostPoints = max($points);
//Output table rows
for($i = 0; $i < sizeof($players); $i++) {
if($points[$i]==mostPoints){
//red background
echo '<tr style="background:#F44">';
}else{
echo '<tr>';
}
echo '<td>'.$name[$i].'</td><td>'.$team[$i].'</td><td>'.$number[$i].'</td><td>'.$position[$i].'</td><td>'.$points[$i].'</td></tr>';
}
I haven't tested this, so there may be a few things in there that I've missed, but it should work. See Array Multisort, and max functions. It may be better to assign a class to the red table row, instead of a style; that way you can alter the td tags; I think that's more browser-friendly. The CSS for that would be something like .redRow td {background:#F44} if you gave the tr the redRow class.

Categories