Php fill array with for loop - php

I'd like to fill an array with data from my database. I created a for loop for that but I think I'm doing something wrong (I'm still very new to programming so sorry for that!)
for($i=0; $i<count($uploadprofile->getAgencies()); $i++){
foreach($uploadprofile->getAgencies() as $agency) {
$users[$i] = $agency->getAgencyUser();
}
}
dump(count($users));
The dump statement only counts 1 user even though there are supposed to be 3 users in there.
I need this array for then using the data in an other for loop afterwards:
for($i=0; $i<count($users); $i++){
foreach($users as $user){
$manager->addNotification($user->toArray()[$i], $notif);
}
}
I am sure this is really bad coding. It looks like way too many lines for something that simple. So I would be really glad about any advice rather than just a "downvoting"!
If more information about the entities are needed, I'd be happy to provide them!

Unless I'm missing something, you have too many loops, and I would stick with foreach. To build the $users array:
foreach($uploadprofile->getAgencies() as $agency){
$users[] = $agency->getAgencyUser();
}
To use it:
foreach($users as $user){
$manager->addNotification($user->toArray(), $notif);
}
But, if you won't actually need the $users array after this then just combine:
foreach($uploadprofile->getAgencies() as $agency){
$user = $agency->getAgencyUser();
$manager->addNotification($user->toArray(), $notif);
}

Related

PHP: How to search in array of objects and return the res

I have this Array of Objects and I want to search a string to all of the keys and return all the data of the matched objects.
I don't know if there's a duplicate of this question.
hope you guys can save my day.
the photo below is my code. I don't use eloquent btw and the data is from call-in SQL.
Below is the UI that I made.
You want to use the pluck method from laravel(eloquent)
So something like this:
$plucked = $paginatedItems->pluck('item_code', 'unit_measure');
$plucked->all();
See: https://laravel.com/docs/8.x/collections#method-pluck
Without seeing your code, it's difficult to determine which approach would be best. However, there are a few ways of doing this. Below are some untested examples. But please use them as examples as there are far easier and better ways of doing this. I am simply trying to point you in the right direction.
$array = array_search([SEARCH TERM], array_keys([YOUR ARRAY]));
$results = [];
$array_keys = array_keys([YOUR ARRAY]);
for($i = 0; $i < count($array_keys); $i++) {
if($array_keys[$i] == "[SEARCH TERM]") {
$results[] = $[YOUR ARRAY][$i];
}
}
Also try: php search array key and get value
Edit: this is pure PHP - as you are using laravel, there are definitely better ways of doing this. Please read the documents for pluck

re-organise a result array from db-query in codeignitter

i have a array of results from a database query.
Now, i need the array in a little bit other structure as it comes from the database query.
I do this for the moment.
$this->db->where($where);
$all=$this->db->get('my_table')->result_array();
after that i reorganize in this way
foreach($all as $element)
{
foreach($element as $subkey=>$subelement)
{
$preset_templates[$element['emailtemplateid']][$subkey]=$subelement;
}
}
Is there a easier or shorter way to do the same?
May be you can try below given code.
foreach($all as $element=>$subelement)
{
$preset_templates[$subelement['emailtemplateid']]=$subelement;
}
I hope it helps.

Encoding Json Correctly?

Alright, So I'm redoing my question so people can understand what I'm trying to do.
Search.php
<?php
$getItems = file_get_contents('Items.json');
if(isset($_GET['searchVal'])){
$getItems2 = json_decode($getItems, true);
$data2 = array("items" => array(array()));
foreach($getItems2['items'] as $data){
if(strpos($data['name'], $_GET['searchVal'])){
$data2 = array("items" => array(array($data)));
}
}
echo json_encode($data2,JSON_UNESCAPED_SLASHES);
} else{
echo $getItems;
}
Problem: Doesn't get all items which have that name, gets only one.
Search is done, now I have to fix somehow to get all items which match the name. How could I do that?
You have the following inside a loop:
$data2 = array(...)
...and then you reference $data2 outside the loop.
Of course, it will only contain the last entry, because that line is overwriting $data2 with new data each time the loop iterates.
If you want to keep all the records from the loop, use
$data2[] = array(...)
instead.
[EDIT]
Further guessing as to what you actually want your JSON to look like, I guess you want all the records to be in the items array?
So in that case, let's rewrite your $data2 line, as follows:
$data2['items'][] = array($data);
This will add all the data arrays to your items array in $data2. I will note that your array structure is really convoluted -- too many nested arrays, which makes it difficult to be sure I'm giving you the answer you want even now, but hopefully if it isn't exactly right, it will show you the direction you need to go.
You'll also want to have an additional line at the top of your code to initialise $data2, like this:
$data2 = array('items'=>array());
This should be somewhere at the top of the code, before $data2 is used, and outside of the loop.

How to get data from multiple collection in loop

When I try to get data from multiple collections code it is giving me data only from the first collection
i.e collections are project_0, project_1, project_2, project_3
for($i = 0; $i <= 3; $i++){
$dm->getClassMetadata('\Application\Document\Product')->setCollection('product_'. $i);
$record = $dm->getRepository('\Application\Document\Product')->findOneBy($condition);
print_r($record);
}
I tried to clear flush but noting is working. Please let me know the right way to do it?
Executing the code above will save the information only from the last collection in $record as you are overwriting the data in it with every iteration.
To fix it, you can create an array, let's say $records = array(); and then in each iteration you can do something like this:
array_push($records, $dm->getRepository('\Application\Document\Product')->findOneBy($condition));
After you're done, you'll have all the data in $records. I hope that helps.

Checking if value in slave array exists in master array Quickly without loop via PHP

In my PHP application. I am taking value from user and all these user values are stored in Array. And just for validation. I am comparing user input value with my array. :-
<?php
// Current Code
$masterArray = array(......); // ..... represents some 60-100 different values.
foreach($_POST as $key => $value) {
if(in_array($value, $masterArray)) {
$insertQuery = $mysqli->query("INSERTION stuff or Updating Stuff");
} else {
echo "Are you tampering html-form-data ?";
}
}
?>
But this is so worthless code, as it takes quite good time in updating or insertion.
Is there any better function that is way faster to check if value in slave array exists in master array ?
From Slave Array i Mean => List / Array of User Input value.
From Master Array i mean => List of my array value stored in page.
Thanks
I think i got the better option with array_diff.
Please let me know if i am doing anything wrong in below before i put this code in production page:- Thanks a lot for your efforts #J.David Smith & #grossvogel
<?php
$masterArray = array(.......); // My Master Array List
$result = array_diff($_POST['checkBox'], $masterArray);
if(count($result) > 0) {
// If they are trying to do some tampering , let them submit all again.
echo 'Something is not Right';
} else {
// If Person is genuine, no waiting just insert them all
$total = count($_POST['checkBox']);
$insertQuery = "INSERT into notes(user,quote) values ";
for($i=0;$i<=$total; $i++) {
array_push($values, "('someuser','".$mysqli->real_escape_string($_POST['checkBox'][$i])."')");
}
$finalQuery = $mysqli->query($insertQuery.implode(',', $values));
}
?>
Is my Code Better , I am testing it in localhost i don't see much of difference, I just want to know expert views if I am messing arround with something ? before i put this code in production page.
Update : This looks pretty better and faster than code in question.
Thanks
The only other way to do this is to use an associative array with your values as keys (well, you could custom-implement another storage container specifically for this, but that'd be overkill imo). Then, you can check with isset. For example:
$masterArray = array(....); // same thing, but with values as keys instead of values
foreach($_POST as $key => $value) {
if(isset($masterArray[$value])) {
// do stuff
} else {
// do stuff
}
}
I'm kind of curious what the point of doing this is anyway, especially given the statement printed by your echo call. There may be an even better way to accomplish your goal than this.
EDIT: Another method suggested by grossvogel: loop over $masterArray instead of $_POST. If you expect $_POST to be a large set of data consistently (ie most of the time people will select 50+ items), this could be faster. Hashing is already very fast, so you'll have to benchmark it on your code in order to make a decision.
$masterArray = array(...); // either style of definition will work; i'll use yours for simplicity
foreach($masterArray as $value) {
if(isset($_POST[$value])) {
// do stuff
}
}

Categories