Save _POST values to an array - php

I have an array of the names of my POST variables to use when I update a row in my database.
$jobs = array( "proposal_id",
"will_provide",
"general_scope",
"per_bid",
"job_type");
Using this style my table is called jobs and each value in the array is a column id.
I want to edit this array so each item (column id) contains a single _POST Value
Then I have a function that uses the variables to create generic queries.
function save_data($jobs) {
foreach ($jobs as $job)
{
$job[$job[$i]] = _$Post[$job];
or
Table_name[column] = cell value;
...
...
...
I would like to be able to save $values into the post variables associated to it. Something like
For example if I was going to manually create this array it would look like
$jobs = array('proposal_id' => '12345678','title_of_project' => 'aTitle','creator' => 'aUser','last_modified' => '0000-00-00','date_created' => '0000-00-00','price' =>'1000');

This should be what you're looking for:
$jobs = array( "proposal_id",
"will_provide",
"general_scope",
"per_bid",
"job_type");
$jobValues = array();
foreach($jobs as $job) {
$jobValues[] = isset($_POST[$job]) ? $_POST[$job] : null;
}
$jobs = array_combine($jobs, $jobValues);

Related

Cannot foreach over an array of objects in a Laravel POST

I have an array of objects which have been posted from a Vue Axios function, which I wish to loop over and save into a database. They are answers to a question.
I have passed in $data which is the array of answer objects (each has a content, correct and mark property), and the $id of the question they belong to. When I return $data, it shows me the array of objects with all the correct properties. When I return $data[0], I can access the first object. But when I try and foreach as below, it complains that $content doesn't exist. Running count() on $data also errors. What is wrong here?
Route::post('answers/{id}', function (Request $data, $id) {
foreach ($data as $value) {
$post[] = [
'user_id' => 1,
'question_id' => $id,
'content' => $value->content,
'correct' => $value->correct,
'mark' => $value->mark
]);
}
Answer::save($post);
});
You are trying to iterate over the hole $request object, which is an instance of the Request class. To access the received values first get them:
// To get all the data
$data = $request->all();
// or..
// To get just a specific value
$data = $request->get('key');
// or..
// only a list of allowed elements
$data = $request->only('here', 'goes', 'your', 'keys');
So, in case your frontend are sending an array of items under the key items. Just get them like mentioned above:
$items = $request->get('items');
Then you can use the foreach():
$items = $request->get('items');
foreach($items as $item)
{
// your operations
}
You can read more about Retrieving Input, in the documentation.

Fill one array using two loop

I have an object where there are all my articles.
I'm currently looping my object to fill an array where I create an associative table for each article.
In my object I also have a Categories object and I would like to add the label of each category at the end of each associative array previously completed, but
I don't know how to do that.. In the Categories object there may be multiple labels.
My code :
$articles = $this->entityManager->getRepository('SGBundle:Article')->findBy([], ['id'=>'desc']);
$arrayCollection = [];
foreach($articles as $article) {
$arrayCollection[] = [
'id' => $article->getId(),
'date_publication' => $article->getDatePublication(),
...
];
foreach($article->getCategories() as $categorie) {
$arrayCollection[] = ['categorie' => $categorie->getLibelle()];
}
}
On my screenshot, for each article there is an array with 36 values ​​and an array with 1 value and I would like this table to be in the table where there are 36 values. It's possible ?
First gather categories, then add'em to article item:
foreach($articles as $article) {
$categories = [];
foreach($article->getCategories() as $categorie) {
$categories[] = $categorie->getLibelle();
}
$arrayCollection[] = [
'id' => $article->getId(),
'date_publication' => $article->getDatePublication(),
...
//
'categorie' => $categories,
];
}
If the article.categories field is marked as lazy, then it won't be hydrated by default and the $article->getCategories() will perform a new query on each loop round.
Instead of a simple findBy, you might want a custom DQL query in this case to optimize this and get the exact array you want in one single request.
Also note that your current query is fetching all articles of your database. While this is probably your purpose, keep in mind that this could get pretty heavy with the data growing. In most cases, this kind of query should be paginated.

post an array and iterate throught it in PHP codeigniter

This is the first time i create my own webservice (someone always did it for me before), so please bear with me.
I post this array :
$data = array(
'user_id' => $this->post('user_id'),
'group_id' => $this->post('group_id'),
'child_id' => $this->post('child_id'), //will be nested array
'custom' => $this->post('custom'),
'time' => $this->post('time'),
'date' => $this->post('date')
);
I tried to create a nested array with this : $this->post('child_id'), because user can post multiple child_id at once.
Then i tried to iterate through the child_id, because i need to insert them to the mysql :
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
What should i do, so i can have an array of child_id in my $data array? (nested array)
And how to iterate through it?
UPDATE :
I have updated the codes above.
I use advanced rest client for testing, and i tried to post something like this in the form content type :
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
Notice that theres two child_id (left most and right most), but only the last one (right most) is inserted.
And this is the add_trans in the model :
function add_trans($table, $data, $schedule_id) {
$query = $this->db->insert($table, array('child_id' => $data['child_id'], 'schedule_id' => $schedule_id));
return $query;
}
Thanks a lot for your time.
Even thought you set the name attribute as child[] on the markup,
You still need to call it as:
'child_id' => $this->post('child_id')
It will still return an array.
for($i = 0; $i < sizeof($data['child_id']); $i++) {
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
EDIT:
Looking upon you query string, that seems to be the culprit:
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
^ same index , same index, same index, it will overwrite and you will get only `2`
If you want to get them all into an array format, you need to set them like this
child_id[]=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id[]=2
^ it needs to be set like this
UPDATE:
And in your model, if you want each id per row, well you can also loop in this case:
function add_trans($table, $data, $schedule_id) {
foreach($data['child_id'] as $child_id) {
$query = $this->db->insert($table, array('child_id' => $child_id, 'schedule_id' => $schedule_id));
}
// return $this->db->insert_id();
return $query;
}
ofcourse that won't work, it has to be
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data['child_id'][$i], $result_id[0]['id']);
}
because you've not set $data['child_id[]'] so it doesn't exist, the key is just a string or number, it does not validate or parse anything
you don't need to give child[] in post method. just give only child, it will get complete array what are you sending from views
replace
'child_id' => $this->post('child_id[]')
with
'child_id' => $this->post('child_id')

Laravel get element of array by key

I have array of objects users. Entity User has two fields: firstName and lastName;
In my controller I add all users to the some array which called employees.
$employees = array();
foreach($users as $user) {
$employees[] = $user->firstName;
}
How can i get on the view element of array by firstName.
I tried like this:
$employees['John'] but it doesn't work
Thanks in advance
The way that you are doing it you are just appending a string to an array. The keys of the array will be integers starting from 0.
To get the user first name as the index, set the Key of the $employees array to be the $user->firstName, then in that position store the object of the $user. Here is the code fixed:
$employees = array();
foreach($users as $user) {
$employees[$user->firstName] = $user;
}
After that you should be able to do $employees['John'].
Remember that to be able to use the array in the View you must pass the array to the view. Ex:
In your controller method you should have something like this:
return View::make('nameOfFile')->with('employees', $employees);
When you add the names to the array you will have something like this:
array(
[0] => "John",
[1] => "Martha",
...
)
You need to access the names by index and I would not suggest having name in the index, what if two users have the same name? You'll end up overwriting one in the array:
Array("John", "John", "Martha")
After having an array with the key as name you end up with:
Array(
[John] => someUser, // <- here you lost one John.
[Martha] => SomeUser,
)
You are appending to an ordinary array, which means that the array keys will automatically be integers in increasing order starting at zero. Suppose we have the "Alice" and "Bob" in the $users array, you code will yield an $employees array with two elements : $employees[Ø] = "Alice" and $employees[1] = "Bob".
To get the result you want you need to use the $user->firstName value as a key:
$employees = array();
foreach ($users as $user) {
$employees[$user->FirstName] = $user->firstName;
}
Although that wouldn't be very useful, I think what you actually meant to get is:
$employees = array();
foreach ($users as $user) {
// use the whole object for this user, not only the firstName field
$employees[$user->FirstName] = $user;
}

SQL result to PHP multidimensional array

I'm retrieving some hierarchical data from an Oracle database using the "connect by" function.
Then I populate a PHP array with the result of my query looking like:
while ($row_branches = oci_fetch_array($query_tree)) {
$tree[] = array(
'id' => $row_branches['ID']
, 'parent' => $row_branche['PARENT']
, 'data' => htmlspecialchars($row_branches['NAME'])
, 'level' => $row_branches['LEVEL']
);
}
The field ID is the unique id of the row
The field PARENT is the ID of the parent
The field DATA is the name of the item
The field LEVEL is the level of the row in the hierarchy.
I'd rather have a multidimensional array because my goal is to use the PHP function json_decode().
The depth of the hierarchy is never known in advance.
So my question is:
How could I populate a multidimensional array with the result of my query?
Thanks a million in advance for your answers.
try this
function adj_tree(&$tree, $item) {
$i = $item['ID'];
$p = $item['PARENT'];
$tree[$i] = isset($tree[$i]) ? $item + $tree[$i] : $item;
$tree[$p]['_children'][] = &$tree[$i];
}
$tree = array();
while ($row = oci_fetch_array($query_tree)) {
adj_tree($tree, $row);

Categories