I am trying to build a string made of the results from sql and I do not know how achieve this when the data from the db is bigger than 1.
I was able to do it when the result from the database is one.
$result = $stmt_grade->fetch(PDO::FETCH_ASSOC);
$str ="[{$result['score_access']}, {$result['score_training']},
{$result['score_expectation']}, {$result['score_total']} ]";
but when I needed to loop the fetch_assoc I was not able to assign a value to variables or directly build the string.
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$resultcount['subarea'];
}
I have looked everywhere and did not find any solutions or any similar approach to find inspiration. I hope someone can help me. Thank you in advance!
The most obvious way to do this is loop through all of the responses in a while loop, and continually append to your string using the .= operator. You can tell when you run out of records because $result will be false.
I separated each record with a newline. It also looked like you wanted to count results, so I added that, too.
$str = ""; // start with an empty string
$count = 0;
while ( ($result = $stmt_grade->fetch(PDO::FETCH_ASSOC)) !== false ) {
// increment the record count
$count++;
// add a new line to the output string
$str .= "[{$result['score_access']}, {$result['score_training']},{$result['score_expectation']}, {$result['score_total']} ]\n";
}
That should do it.
All you need is to name your string properly.
And then use a proper way to create a JSON string. Which consists of two parts:
Create a array of desired structure. Or at least provide a that structure here to let us to provide you with the code.
Use json_encode().
Assuming you need a nested array like this
[[1,2,3],[1,2,3],[1,2,3]]
the code would be
$result = $stmt_grade->fetchAll(PDO::FETCH_NUM);
echo json_encode($result);
thanks for all the answers provided without you I could not made it. Finally, I achieved the desirable result as follow, probably it is not elegant but works:
$stmt_count= $user->countbyespeciality();
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$prueba.= "{$resultcount['subarea']},";
$prueba2.= "{$resultcount['number']},";
}
$string=rtrim($prueba, ",");
$string2=rtrim($prueba2, ",");
$final="[{$string}]";
$final2="[{$string2}]";
The output is [something,something] [1,2,] as expected.
thanks again!
Related
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
With the updated code below, my search is working, but only using the last word in the Array. Is there a way to search the MySQL column using all words the user inputted?
Note: All input sanitization and escaping is completed in my code but not shown here.
I have two PHP arrays: $search_exploded (user inputted search terms) and $metaphoneArr (metaphones of keywords in MySQL).
I'm cycling through $search_exploded and $metaphoneArr, and if the Levenshtein is less than 2, then I'm adding the metaphone element to a third array called $levenResultsArr.
In MySQL, I'm joining two tables, and if there's a result in my third array ($levenResultsArr) that matches a row in my metaphone_col, then I want the results printed. Somehow, though, I am not referencing the third array correctly in the MySQL statement.
Any advice? Here is part of my PHP code.
$levenResultsArr = array();
foreach ($search_exploded as $search_each => $searchWord) {
$search_each2 = metaphone($searchWord);
echo $search_each2 . "<br/>";
foreach ($metaphoneArr as $metaword => $val) {
$lev = levenshtein($search_each2, $val);
if ($lev < 2) {
array_push($levenResultsArr, $search_each2);
}
}
}
// And shown below is the MySQL statement
$constructs = "
SELECT vt.idvideolist,
vt.videotitle,
vt.videodescription
FROM videolist_tbl vt
INNER JOIN keyword__video k2v ON (vt.idvideolist = k2v.video_id)
INNER JOIN keywords_tbl k ON (k2v.keyword_id = k.idkeywords_tbl)
WHERE k.metaphone_col = '$search_each2'
";
It's only searching using the last word in the array instead of all words in the array.
You're correct that you aren't referencing your array correctly in your query. You are simply referencing the variable '$search_each2'. You want to check the entire array. The best way to do this would to be to convert the array to a string using implode and using the MySQL IN clause. We need to modify the array first to format it correctly:
foreach($levenResultsArr as &$foo){
$foo = "'".$foo."'"; //add single quotes around each object in the array
}
$levenAsStr = implode(",", $levenResultsArr);
Then simply change your last line to the following:
WHERE k.metaphone_col IN (".$levenAsStr.")";
Did this from memory because I'm not in a testing environment, please let me know if there are any syntax errors. Should work for you!
Without seeing more of the code its a bit difficult to determine what is going on. A couple of thoughts though.
What var is the array containing all search terms?
I noticed you are pushing items into $levenResultsArr. I don't see it being used in the query though.
If it is $search_each_2 you may try using the IN syntax:
WHERE k.metaphone_col IN '$search_each2';
This will only match exact values however. i.e.:
some value does not return if the IN array contains value. The array would have to contain some value
If you need it to match partial searches you may try using LIKE with wildcards: %
WHERE k.metaphone_col LIKE "%searchTerm1%"
OR k.metaphone_col LIKE "%searchTerm2%"
OR k.metaphone_col LIKE "%searchTerm3%"
You could potentially use the implode function to create the sql string from the array: http://php.net/manual/en/function.implode.php
I am working on an import script that needs to evaluate whether the set string fits with the possible values the backend field can have.
More exactly what I have is this array of committes:
$committees = array(
'Ämter' => 1,
'Abteilungen' => 2,
'Konservatoren' => 3,
'Dienstagssitzung' => 4,
);
and now I need to figure out if a string saved in
variable $category matches any key in that array. If it does match one of the entries, I need it to return the value (1, 2, 3 or 4) that goes with that key.
I read up about it here on Stackoverflow and found plenty examples to see if a value equals one in an array, for example:
preg_match array items in string?
and tried to follow those along.
I tried
$committeesKeys = '/(' . implode('|', array_keys($committees)) . ')/';
$matches = preg_match($committeesKeys, $category);
but that only returned how many matches it found?
I also tried
$input = preg_quote($category, '/');
$matches = preg_filter('/'.$input.'/', null, $committees);
as that was suggested somehwere else, can't find the link anymore, but that returned an empty array.
I am new to all of this so might be totally wrong here.
Can anybody tell me how I can do this, or where I can find an answer to the question? I might just not have found it, my brain is rather tired right now...
I feel that I have right to post that as answer accepted :-) :
echo (isset($committees[$category]))?$committees[$category]:'There is no '.$category.' category';
you can do something like this:
function getValue($category){
if (array_key_exists($category, $committees)){
return $committees[$category]; //the value you want
}
}
Hope this helps :)
preg_match() has a 3rd argument which will allow you to save capture groups into a numerical array. However, if you want to compare a string directly you can simply use a loop and strcmp or === which will probably work faster since preg_match has to compile the regex you define in the first argument. My solution for this problem would look like:
$found = FALSE;
foreach ( $committees as $name=>$number ) {
if ( $name === $category ) {
$found = $number;
}
}
return $found;
You make it difficult by not showing what is in the category matches.
Maybe something like this.
$results = array_intersect ($matches,$committees );
Hello My question is that i will have a textarea which i want to paste the following
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there any way i can run a loop which allows me to manipulate the data individually so i can update this to the database. so the first time i run the loop is get this:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
if possible i want to strip out the {'s and :'s and "s so i am left with the commas and the data. For example:
1173627548,methv,dont know.. etc
sorry if i am unclear with my question in any way.
$myhugejson = 'blah...';
$array = json_decode($myhugejson, true);
foreach($array as $sub) {
print_r($sub);
echo $thing = $sub[0]['methv'];
echo $second = $sub[0]['q1'];
}
In each iteration, $sub should contain your list.
All of this is assuming you're using JSON, which I think that is.
To reference i
I had this working by simply passing the data from one variable to another like so:
$CalcsSets = $DisplayCalcs;
without the need to use the loop inside the first if() statement and it inserted the data without quotes but all of a sudden it's stopped working and I'm not sure why (it only started showing last integer), so I went with the more complex code trying to get it to work again as shown below.
Here's the complex code I'm working with:
for($i=1; $i<=$CalcSets; $i++){
$calculations = PerformCalc($min, $highest, $OperatorType);
echo 'Calculations performed for '.$SetText[$i];
foreach ($calculations as $key => $DisplayCalcs) {
echo $SetCalc[] = $DisplayCalcs.', '; //stores calculations with ',' in
//array.
}
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults = $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
What it's supposed to do is insert values in the following format (1,2,3,4,5,) into the database in a VARCHAR row but now all it shows is the last integer with no comma. I originally wanted to just store the integers and not a comma but I couldn't get it to display on the page with commas after each integer so I went this route as mentioned earlier.
I realize I'm probably going about this the wrong way, but if any of you know a much easier, and shorter, way to do what I want, I'd be extremely appreciative of the help.
Reason I'm doing it this way, is because on the results page, it needs to show in the format mentioned above.
FYI, I did check the DB row and it is still set to VARCHAR with a length of 10 at the moment.
UPDATE TO MAKE INTENTIONS MORE CLEAR
Ok, I'm going to go back to square one and try to make my intention as clear as possible. I've been rewriting this code snippet more times than I care to count and my brain is all foggy lol.
array1 = array(1, 2, 3, 4, 5, 6);
foreach(array1 as $key => $data){
echo $data.',';
// will display 1,2,3,4,5,6, in browser.
}
if(is_true == 1){
INSERT ALL $data values into DB here.
}
That's what I'm trying to accomplish in it's simplest form, I'm just have extreme difficulty achieving my goal.
Second Update - Topic Solved
Apparently, the DB field had to be set to Text rather than VarChar. I guess we learn something new everyday.
Again, thanks everyone for all of your help. It was greatly appreciated!
I'm sorry but I couldn't make much sense from the original code but focusing only on the last IF and the containing LOOP, I think the problem is with the assignment statement:
$SetResults = $SetCalc[$i];
It should instead use .= for concatenation. Here is how it should look:
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults .= $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
Hope it works!
I completely agree with the solution from #KemalFadillah for using the implode() method. From your code snippet, I understand that $calculations is the array that stores the main values, i.e. Array(1, 2, 3, 4, 5). So you can do:
$calculations = PerformCalc($min, $highest, $OperatorType);
$s = implode (', ', $calculations);
DB_Insert($s);
I hope that makes sense?
You are executing the last for loop only if $calcSets == 1 and have an $i<$calcSets condition
How about doing it like this
$SetCalc = "";
foreach ($calculations as $key => $DisplayCalcs) {
echo $SetCalc .= $DisplayCalcs.', ';
}
DB_Insert("(".$SetCalc.")");
You're looking for the implode() function to format the numbers.
$formatted = implode(',', $calculations); // Produce 1,2,3,4,etc...
http://php.net/manual/en/function.implode.php