I'm building an Insert query using Faker and I wonder whether it is possible to use a value to-be-inserted in another value.
Here is an example, not accurate for my situation but explains well:
DB::table('debts')->insert([
'name' => $faker->company,
'debt' => $faker->randomFloat($nbMaxDecimals = 2, $min = 20000, $max = 10000000),
'debt_paid' => 'debt' / rand ( 2 , 8 ),
'notes' => $faker->paragraph($nbSentences = 3, $variableNbSentences = true),
]);
As you can see, in the row of debt_paid I want to access the value of 'debt' that was randomly defined a row above. This is because debt_paid needs to be logical and without the value of debt it might be non-sense.
I know that defining 'debt' as a variable before the insert would solve it, but I wonder whether there's a more elegant solution.
So do that outside the insert
$dbt = $faker->randomFloat($nbMaxDecimals = 2, $min = 20000, $max = 10000000);
DB::table('debts')->insert([
'name' => $faker->company,
'debt' => $dbt,
'debt_paid' => $dbt / rand ( 2 , 8 ),
'notes' => $faker->paragraph($nbSentences = 3, $variableNbSentences = true),
]);
Related
I am trying to merge two results of two queries in MYSQL using PHP, but I am puzzled how to do it! I am using PDO. I am programming for a hobby and am trying to make a to do list app just like a Trello board. However, I just can't figure out how to merge two results from different tables in a database.
The idea is as follows:
I have a table called 'task_lists' with the content:
'list_id => 1, list_name = 'listOne'
'list_id => 2, list_name = 'listTwo'
And a table called 'tasks':
task_id => 1, list_id => 1, task_name => 'taskOfListOne', duration => 5, is_done => 1
task_id => 2, list_id => 1, task_name => 'anotherTaskOfListOne', duration => 5, is_done => 1
task_id => 3, list_id => 2, task_name => 'taskOfListTwo', duration => 10, is_done => 0
And I am trying to create an array that is merged between the two results as something like:
(I know this is a rough picture of how the array is supposed to look like)
$result = [array]
[list_id] = 1, [list_name] = 'listOne' =>
[array][list_id] = 1, ['task_name] = taskOfListOne,[duration] = 5, ['is_done'] => 1
[array][list_id] = 1, ['task_name] = anotherTaskOfListOne,[duration] = 5, ['is_done'] => 1
[list_id] = 2, [list_name] = 'listTwo' =>
[array][list_id] = 2, ['task_name] = taskOfListTwo,[duration] = 5, ['is_done'] => 1
Is this even possible? I have tried a Union sql query and methods like nested foreach statements, but none of them worked for me. Am I missing something here?
PS: Sorry for my bad english.
Have you tried a left join?
SELECT TL.`list_id`, TL.`list_name`, T.`task_name`, T.`duration`
FROM task_lists AS TL
LEFT JOIN tasks as T ON TL.`list_id` = T.`list_id`
And then in PHP you build the array in the format you want.
Later edit:
Simple PHP example to parse SQL data as you asked (to remove duplicated info):
<?php
// $mysql_rows -> here is your query result, fetched as associative array
$filtered_array = array();
foreach ($mysql_rows as $row){
// Initiate record if is not already initiated
if (!isset($filtered_array[ $row['list_id'] ])){
$filtered_array[ $row['list_id'] ] = array(
'list_id' => $row['list_id'],
'list_name' => $row['list_name'],
'tasks' => array()
);
}
// Add tasks
$filtered_array[ $row['list_id'] ]['tasks'][] = array(
'task_name' => $row['task_name'],
'duration' => $row['duration'],
'is_done ' => $row['is_done ']
);
}
// Optional: if you want to remove list_id from $filtered_array key names, uncomment the next line
// $filtered_array = array_values($filtered_array);
?>
Consider the following:
$characterStats = [
['strength' => 500],
['dexterity' => 200],
['agility' => 1000],
['intelligence' => 1200],
['health' => 675],
];
$stat = array_search(max($characterStats), $characterStats);
echo $stat;
What I expect: ['intelligence' => 1200]
What I get: 0
Can some one help me out to achieve what I want?
Try the following:
$characterStats = array(
'strength' => 500,
'dexterity' => 200,
'agility' => 1000,
'intelligence' => 1200,
'health' => 675,
);
$stat = array_search(max($characterStats), $characterStats);
echo $stat;
I changed the way the array is declared. I believe you may need to indicate the field name you would like to search if using nested arrays with the following call:
$stat = array_search(max($characterStats), array_column($characterStats, 'KEYNAME'));
However, since each sub array has only 1 element with different "key" it may not be the best approach. For your scenario, you may need to use another approach, where you loop through each element and store the max value found.
With the array as you have it at the moment, the easiest way I can think of doing it as a standard foreach() and keep the maximum value as well as the element where it's found (save doing another search to get the full entry)...
$characterStats = [
['strength' => 500],
['dexterity' => 200],
['agility' => 1000],
['intelligence' => 1200],
['health' => 675],
];
$maxStat = null;
$max = null;
foreach ( $characterStats as $stat ){
if ( current($stat) > $max ) {
$max = current($stat);
$maxStat = $stat;
}
}
print_r( $maxStat);
I'm using Faker in my Laravel 5.5 project to fake some data.
I ran into this issue where I need to set two other columns inside the faker to the same value as the "live" column that was generated. Here is what I mean:
$factory->define(App\File::class, function (Faker $faker) {
return [
'identifier' => uniqid(),
'user_id' => App\User::all()->random()->id,
'title' => $faker->sentence($nbWords = 4),
'overview_short' => $faker->sentence,
'overview' => $faker->text($maxNbChars = 500),
'price' => $faker->randomFloat($nbMaxDecimals = 2, $min = 0, $max = 125),
'live' => rand(0, 1), // So if "live" = 1
'approved' => rand(0, 1), // Then I want "approved" = 1
'finished' => rand(0, 1), // And "finished" = 1
];
})
So if the "live" column gets set to 0, then I want the "approved" and "finished" columns set to 0, or other way around. And the "live" column can be random, 0 or 1
Is there a way to do this in Faker?
// ---------------
Got it,
$live = rand(0, 1);
return [
// .......
'live' => $live,
'approved' => $live,
'finished' => $live
];
you should store the random variable be stored into $live, and set 'approved' and 'finished' according to the value
Im trying to make a multidimensional array with two columns. Name and Counter. I can do a single array with all the names. But I dont know how to make it multidimensional and be able to still update the counters. Code i got so far is
if (!in_array($prodname, $da)){
array_push($da, $prodname);
}
and then I can dump it back out with a foreach. How do I make it two dimensional? How can I say alright this exists update the old value? etc.
If you only need name and counter then you should just be able to use a normal array:
$nameCountArray = array();
foreach($names as $name){
if(!array_key_exists($name,$nameCountArray)){
$nameCountArray[$name] = 1;
}else{
$nameCountArray[$name] = $nameCountArray[$name] + 1;
}
}
If you do need multidimensional arrays these are just arrays of arrays and can be accessed as such. A good example of this is using a 2d array to store locations (say on a 3 by 3 grid):
$twoDArray = array(
0 => array(0 => 1,
1 => 4,
2 => 7),
1 => array(0 => 2,
1 => 5,
2 => 8),
2 => array(0 => 3,
1 => 6,
2 => 9)
);
//Grab the item at 1,2
$item = $twoDArray[1][2];//Will give '8'
Supposing you want $da to look like this:
Array(
"name1" => array("score1" => 80, "score2" => 100),
"name2" => array("score1" => 50, "score2" => 60),
"name3" => array("score1" => 90, "score2" => 80),
...
)
Then all you need to do is something like:
function setScore($prodName, $scoreName, $score)
{
global $da;
if (!array_key_exists($prodName, $da)) {
$da[$prodName] = array();
}
$da[$prodName][$scoreName] = $score;
}
setScore("name1", "score1", 80);
setScore("name1", "score2", 100);
setScore("name2", "score1", 50);
...
Unless I'm misunderstanding your question, which is very possible.
I'm working on a rating system. When a user rates, $inc increments the field, and addToSet adds the user_id to make sure the user only clicks rate once. I am checking if the user_id is already in the x field before updating, but that is another query which I'd rather avoid. Can I reach this purpose without having to write another query? I mean, $addToSet only adds if there is no value like that; can I instead get affected rows? Can you suggest other queries?
Thank you!
..->update(
array("_id" => $idob),
array(
'$inc' => array($type => (int) 1),
'$addToSet' => array("x" => (int) $user_id)
)
);
Ok I see the problem.
..->update(
array("_id" => $idob),
array(
'$inc' => array($type => (int) 1),
'$addToSet' => array("x" => (int) $user_id)
)
);
The problem is that you need a conditional $inc there so that it only $incs if it does add to set.
This is not possible with a unique index since unique indexes work from the root of the document atm. Also you probably want to use the $inc as a form of pre-aggregation or what not.
One method could be:
update(
array('_id' => $idob, 'x' => array('$nin' => array($user_id))),
array(
'$inc' => array($type => 1),
'$push' => array('x' => (int)$user_id)
)
)
This will only do the update if that user_id does not already exist in x.