I have a multidimensional $array. One of its column is customer name.
I have to save all the rows of array in a db, except for the rows with the same customer name.
I've written a function called searchMultidimensionalArray which creates an array that contains all the rows with different customer name. Before inserting a row in the db, I search for the current row in that array. If present, I do nothing, else I store the current row.
Here's my solution, but It's not working properly.
public function searchMultidimensionalArray($valueName, $arrayCustomer)
{
foreach ($arrayCustomer as $key => $val) {
if ($val['name'] === $valueName) {
return true;
}
return false;
}
}
This is where I loop through the array:
for ($i = 1; $i < $countArray; $i++) {
$customer = new Customer();
$customer->setName($customerName); // I already have $customerName data
if ($i == 1) {
$arrayCustomer[$i] = [
'name' => $customerName,
];
$em = $this->getDoctrine()->getManager();
$em->persist($customer);
$em->flush();
}
if ($this->searchMultidimensionalArray($customerName, $arrayCustomer) == true) {
$repository = $this->getDoctrine()->getRepository('AppBundle:Customer');
$customer = $repository->findOneBy(['name' => $customerName]);
} else {
$em = $this->getDoctrine()->getManager();
$em->persist($customer);
$em->flush();
$arrayCustomer[$i] = [
'name' => $customerName,
];
}
}
Unless I am misunderstanding your case, the desired result can be efficiently achieved a couple of ways.
The DB way: Set up your database table so that the name column is a unique key. That way if you try to INSERT a duplicate, the row will fail as desired.
The PHP way: I would recommend array_column() and array_unique() like this:
$unique_customer_names=array_unique(array_column($arrayCustomer,'customer_name'));
Then use $unique_customer_names to identify duplicates.
I hope one of these options provides a preferable solution for you.
Related
Hello There I need Help To Update on Vehicle Wies on Specific Dates.I'm Attaching Form image and Here is my Controller code.
public function add_vehicle_expense(Request $request)
{
$veh = array('veh_reg_num' => $request->veh_reg_num);
foreach ($veh as $data) {
print_r($request->date[$data]);
dd();
$veh = Sale_report::where('date',$request->date[$data])->where('veh_reg_num', $request->veh_reg_num[$data])->update(['diesel_qty'=> $request->qty[$data], 'diesel_rate'=> $request->rate[$data], 'diesel_amount'=> $request->total_amount[$data], 'other_expense'=> $request->other_exp[$data]]);
}
if ($veh) {
return redirect()->back()->with('Data Store Successfully');
}
//$veh = Sale_report::where('date',$request->date)->where('veh_reg_num', $request->veh_reg_num)->update(['diesel_qty'=> $request->qty, 'diesel_rate'=> $request->rate, 'diesel_amount'=> $request->total_amount, 'other_expense'=> $request->other_exp]);
/* foreach ($request->date as $reg_num => $key ) {
$s = Sale_report::where('date',$request->date[$reg_num])->where('veh_reg_num',$request->veh_reg_num[$reg_num])->first();
$s->diesel_qty = $request->qty[$reg_num];
$s->diesel_rate = $request->rate[$reg_num];
$s->diesel_amount = $request->total_amount[$reg_num];
$s->other_expense = $request->other_exp[$reg_num];
$s->update();
} */
}
I have try to Update Data by matching Each Vehicle Number with Date Some times it Show ErrorException Attempt to read property on int,ErrorException Undefined array key "data"
I have Found The Solution of this Problem.
I've use implode(',' , $request->veh_reg_num) Then I use $datas = explode() function then I use foreach() With exploded Vairable as foreach($datas as $data => $value){
match the each row that with $data array then I Update the values to data base }
I'm Trying to create single array that contains all the ID of parent and child from the database.
But all I was getting is single data.
My ideal output is:
array('160', '161', '162', '163', '164');
what am I getting is only
array('160');
Here is what I've done so far.
public function arrayId(array $elements) {
$where_in = array();
foreach($elements as $element){
if($element->isArray) {
$elems = $this->my_model->select_where('tbl_policies', array('parent_id' => $element->id));
$this->arrayId($elems);
}
$where_in[] = $element->id;
}
return $where_in;
}
$id = 160; //for instance
$elements = $this->my_model->select_where('tbl_policies', array('id' => $id));
$where_in = $this->arrayId($elements);
die(print_r($where_in));
and the data I'm fetching here:
tbl_policies
It's kinda difficult for me to construct questions. So please if something is not clear, do comment below, I'll try my best to make it more understandable. Thanks in advance.
I understand, that you want to delete a parent with all its children and grandchildren. But you do it not directly and sequentially rather want to collect all ids of the records to be deleted. You should go following steps:
Parent-Id (example 160) is already known. Add this to your list.
Write a recursive function such as getChildrenIds(parentId).
Within this function you should iterate over children. And if a child has the flag "isArray" (according to your application logic) then you should call getChildrenIds(currentChildId)
I have written following function. It should work.
public function getChildrenIds( int $parentId, array &$idList) {
$idList[] = $parentId;
$records = $this->my_model->select_where('tbl_policies', array('parent_id' => $parentId));
foreach($records as $r){
if($r->isArray)
$this->getChildrenIds($r->id, $idList);
else
$idList[] = $r->id;
}
return;
}
public function CollectIds(){
$id = 160; //for instance
$where_in = array();
$this->getChildrenIds($id, $where_in);
}
Please notice, that $where_in passed by reference to the recursive function getChildrenIds() and filled there.
Respected Sir/Ma'am, I have different product and I want to create a dynamic $input in controller to save product information into database
Example
$imput['name'] = $request->get('name');
$imput['price'] = $request->get('price');
$imput['description'] = $request->get('description');
To create above input dynamically in controller I try to use foreach loop and pass Input key and value from Frontend side
Example
[["name", "biryani"], ["size", "full"], ["price", "200"], ["description", "chicken + rice"], ["url",
…],…]
0: ["name", "biryani"]
1: ["size", "full"]
2: ["price", "200"]
3: ["description", "chicken + rice"]
4: ["url",…]
5: ["modelName", "chickenBiryani"]
Code i write in controller
(where i do mistake , this code not working also please give answer which I mention in below code comment , Thank You)
public function upload($productInfo)
{
$input=[];
foreach ($productInfo as $data) {
// return $productInfo -- this return data
// return $data -- this return throw error , why this happen
foreach ($data as $val) {
// return $val -- this return data
if ($val[0] == 'modelName') {
$modelName = '\\App\\' . $val[1];
} else {
$input[$val[0]] = $val[1];
}
}
}
$model = new $modelName;
$model::create($input);
return response()->json(['msg' => 'Profile Image Upload Succeessfully']);
}
Please help me sir i am new in Laravel
In your code, you declared $input = [], but using $imput in the loop. That means $input will always be an empty array.
Secondly, Model::create() accepts a single associative array, not multidimensional array e.g:
[
"name" => "Name",
"user_id" => 23
]
Finally, you might need to fletch out your code to eliminate that double loop. But I'm not sure what you're trying to achieve, so can't suggest edits
I have a database with a couple of tables related between them. For example, the table User contains all the users in the system.
Then I have an index table named User_friend with the relation between a user an it's friends.
I have a function loadObject($class, $id) which is called like:
loadObject('User', 1);
and returns the User with id = 1 as an array with the following format:
array(
'id' => 1,
'username' => 'My user',
// the following array contains all the entries in User_invited
'friends' => [2, 3, 4, 5],
// same for comments
'comments' => [6, 7]
'type' => 'User'
);
I'm trying to come up with a recursive function that checks the User with id = 1, finds all the friends (inside the 'friends' array) and then loops through each value, find those Users and it's friends until it reaches the end of the chain without duplicating any entries.
This seems pretty straight forward. The problem is that apart from friends we can have other relations with Comments, Events and many other tables.
The tricky part is that this function should not only work with the 'User' class, but also with any class we define.
What I'm doing is using some sort of Indexed array to define which index tables refer to which main tables.
For example:
$dependencies = [
'friends' => 'User'
];
This means that, when we find the 'friends' key, we should query the 'User' table.
Here's my code:
<?php
$class = $_GET['class'];
// if we receive a collection of ids, find each individual object
$ids = explode(",", $_GET['ids']);
// load all main objects first
foreach($ids as $id) {
$error = isNumeric($id);
$results[] = loadObject($class,$id);
}
$preload = $results;
$output = [];
$output = checkPreload($preload);
print json_encode($output);
function checkPreload($preload)
{
$dependencies = [
'comment' => 'Comment',
'friend' => 'User',
'enemy' => 'User',
'google' => 'GoogleCalendarService',
'ical' => 'ICalCalendarService',
'owner' => 'User',
'invited' => 'User'
];
foreach($preload as $key => $object)
{
foreach($object as $property => $values)
{
// if the property is an array (has dependencies)
// i.e. event: [1, 2, 3]
if(is_array($values) && count($values) > 0)
{
// and if the dependency exists in our $dependencies array, find
// the next Object we have to retrieve
// i.e. event => CatchAppCalendarEvent
if(array_key_exists($property, $dependencies))
{
$dependentTable = $dependencies[$property];
// find all the ids inside that array of dependencies
// i.e. event: [1, 2, 3]
// and for each ID load th the object:
// i.e. CatchAppCalendarEvent.id = 1, CatchAppCalendarEvent.id = 2, CatchAppCalendarEvent.id = 3
foreach($values as $id)
{
$dependantObject = loadObject($dependencies[$property], $id);
// if the object doesn't exist in our $preload array, add it and call the
// function again
if(!objectDoesntExist($preload, $dependantObject)) {
$preload[] = $dependantObject;
reset($preload);
checkPreload($preload);
}
}
}
}
}
}
return $preload;
}
// 'id' and 'type' together are unique for each entry in the database
function objectDoesntExist($preload, $object)
{
foreach($preload as $element)
{
if($element['type'] == $object['type'] && $element['id'] == $object['id']) {
return true;
}
}
return false;
}
I'm pretty sure I'm close to the solution but I'm not able to understand why is not working. Seems to get stuck in an infinite loop even if I'm using a function to check if the object has been inserted in the $preload array. Also, sometimes doesn't check the next set of elements. Could it be because I'm appending the data to the $preload variable?
Any help is more than welcome. I've been trying to find algorithms for resolving dependencies but nothing applied to MySQL databases.
Thanks
After some failed tests I've decided to not use a recursive approach but an iterative approach.
What I'm doing is start with one element and put it in a "queue" (an array), find the dependencies for that element, append them to the "queue" and then step back and re-check the same element to see if there are any more dependencies.
The function to check the dependencies is a bit different now:
/**
* This is the code function of our DRA. This function contains an array of dependencies where the keys are the
* keys of the object i.e. User.id, User.type, etc. and the values are the dependent classes (tables). The idea
* is to iterate through this array in our queue of objects. If we find a property in one object that that matches
* the key, we go to the appropriate class/table (value) to find more dependencies (loadObject2 injects the dependency
* with it's subsequent dependencies)
*
*/
function findAllDependenciesFor($element)
{
$fields = [
'property' => 'tableName',
...
];
$output = [];
foreach($element as $key => $val) {
if(array_key_exists($key, $fields)) {
if(is_array($val)) {
foreach($val as $id) {
$newElement = loadObject($fields[$key], $id);
$output[] = $newElement;
}
}
else {
// there's been a field conversion at some point in the app and some 'location'
// columns contain text and numbers (i.e. 'unknown'). Let's force all values to be
// and integer and avoid loading 0 values.
$val = (int) $val;
if($val != 0) {
$newElement = loadObject($fields[$key], $val);
$output[] = $newElement;
}
}
}
}
return $output;
}
I'm also using the same function as before to check if the "queue" already contains that element (I have renamed the function to be "objectExists" instead of "objectDoesntExist". As you can see I check the type (table) and the id because the combination of these two properties is unique for the whole system/database.
function objectExists($object, $queue)
{
foreach($queue as $element) {
if($object['type'] == $element['type'] && $object['id'] == $element['id']) {
return true;
}
}
return false;
}
Finally, the main function:
// load all main objects first
foreach($ids as $id) {
$error = isNumeric($id);
$results[] = loadObject($class,$id);
}
$queue = $results;
for($i = 0; $i < count($queue); $i++)
{
// find all dependencies of element
$newElements = findAllDependenciesFor($queue[$i]);
foreach($newElements as $object) {
if(!objectExists($object, $queue)) {
$queue[] = $object;
// instead of skipping to the next object in queue, we have to re-check
// the same object again because is possible that it included new dependencies
// so let's step back on to re-check the object
$i--;
}
}
$i++;
}
As you can see, I'm using a regular "for" instead of a "foreach". This is because I need to be able to step forward/backward in my "queue".
I am attempting to log specific actions users are taking on my site and have a listener check if certain entities are being updated, and if so, my goal is to log the fields they are editing, but not all the fields (some are not important or too long).
I have a problem saving the changeset to my database which is why I want to filter for important fields. This works to save the changeset, but when there are several nested arrays within the changeset, the array is not saved correctly (it cuts off after 3 or so arrays within arrays). I am using the array type in postgres. In my postupdate event I have:
if ($entity instanceof ListingQuery) {
$entityManager = $eventArgs->getEntityManager();
$ul = new UserLog();
$uow = $entityManager->getUnitOfWork();
$changeset = $uow->getEntityChangeSet($entity);
$ul = new UserLog();
$ul->setLog($changeset);
$ul->setUser($entity->getUser());
$entityManager->persist($ul);
$entityManager->flush();
}
I've been looking over the docs, but am not really sure how to iterate over the $changeset. It's a multidimension array that can have a variable amount of arrays within based on the number of fields updated. Userlog is a simple entity I have for saving the $changeset and the log field is an array.
I created a function that takes the $changeset and loops through the first three levels of the array, but its not saving the name of the field and only saves the values before and after. How do I access the field names changed in the $changeset?
I think I have a solution that works well. It adds the entity type so it does not match the changeset exactly from Doctrine2, but I think works for my purpose. I found a bunch of other posts form people trying to log specific changes in Doctrine with mixed results so please post if anyone else has a better solution.
public function looparray($arr, $type) {
$recordset[] = array($type);
$keys[] = array_keys($arr);
foreach ($keys as $key) {
if (!is_array($key)) {
if (array_key_exists($key, $arr)) {
$recordset[] = array($key => $arr[$key]);
}
} else {
foreach ($key as $key1) {
if (!is_array([$key1])) {
$recordset[] = array($key1 => $arr[$key1]);
} else {
if (!is_array([$key1])) {
$recordset[] = array($key1 => $arr[$key1]);
} else {
$recordset[] = array($key1 . ' changed ' => $key1);
}
}
}
}
}
return $recordset;
}