How to check if certain value exist in csv file with PHP - php

I've a field in my database which has csv values, if I get the value in a variable it looks like
$data = "dell, dell7, jhon5, doe4";
//these are user id's
I need to check if a certain id is already in this variable.
I used explode() with foreach() and it worked well. But, I need to do this in several times and my code become messy.
Is there any other way?
I'm using Laravel(Lumen)

function checkId($id){
$data = "dell, dell7, jhon5, doe4";
$array = explode(",", $data);
return in_array($id, $array);
}

Another alternative will be preg_match(), like this -
$data = "dell, dell7, jhon5, doe4";
$search = 'dell';
if(preg_match("/\b".$search."\b/i", $data)){
echo 'found';
}
I am not sure about this solution. But this strikes in my mind when I saw your question.

Related

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.

Create a string from a fetch(PDO::FETCH_ASSOC)

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!

How can I convert an array of strings to an array of integers?

I'm getting this error with my current PHP code:
Notice: TO id was not an integer: 1, 2. 1) APNS::queueMessage ->
How can I convert to an array of strings to an array of integers like in this other question: ID not integer... EasyAPNS ?
I'm basically trying to pass ids (from my database,) to newMessage() like this Apple example:
// SEND MESSAGE TO MORE THAN ONE USER
// $apns->newMessage(array(1,3,4,5,8,15,16));
// ($destination contain a string with the Ids like "1,2,3")
Here is my code below:
if (isset($destination))
{
//$destination = 1,2,..
$dest = explode(",", $destination);
if (isset($time))
{
$apns->newMessage($dest, $time);
}
else
{
$apns->newMessage($dest);
}
$apns->addMessageAlert($message);
$apns->addMessageBadge($badge);
$apns->addMessageSound('bingbong.aiff');
$apns->queueMessage();
header("location:$url/index.php?success=1");
}
I would create a wrapper function that accepts an array, and then call it.
function newMessageArray($array) {
foreach ($array as $element) {
$apns->newMessage($element);
}
}
This way, you can call newMessageArray() with an array of integers, such as array(1,2,3,4,5), and they will all be sent.
Also, you should change the variable names (from $array and $element) to something more meaningful. I don't know what you're trying to do, so I wasn't sure what names to use.
Your Question is not clear, It's only a guess work.
It seems to be error in convert integer, try
$dest = explode(",", $destination);
$destArray = array();
foreach($dest as $key => $val) {
$destArray[$key] = intval($val);
}
if (isset($time))
{
$apns->newMessage($destArray, $time);
}
else
{
$apns->newMessage($destArray);
}
Convert where the string is not integer using 'intval'.
I believe what you may be looking for is how to do this:
You have ids in your database table, right? And you are trying to get multiple ids into an array so that the array can be used in $apns->newMessage() call, right? (I checked the source for this...) But, the ids are somehow coming over as strings instead of ints.
So, you probably want to just make sure that the new array is made up of ints, like this:
function to_int($x) {
return (int)$x;
}
$dest = array_map("to_int", $dest);
There are probably other ways to do this, but this way, you at least know that you have int variables in that array. Hope that helps!

PHP, Best way of setting a value in a multi-dimensional array when the pathway is dynamic?

Solution Found: Dynamic array keys
I have a multi dimensional dynamic array, the format of which varies. for example.
$data = array('blah1'=>array('blah2'=>array('hello'=>'world')));
I then have a dynamic pathway as a string.
$pathway = 'blah1/blah2/hellow';
The pathway is broken up into it's component parts, for simplicities' sake:
$pathway_parts = explode('/', $pathway);
My problem arises from wanting to set the value of 'hello'. The way I currently do it is via eval, but I want to illiminate this evil partly because of the php Suhosin hardening breaking the app, but also because I don't believe this is the best way.
eval('$data["'.implode('"]["', $pathway_parts).'"] = $value;');
$data must always return the full array because further down the array it is serialised and stored. What would the best way to transverse the array to set the value without the use of eval?
You can do this using references to gradually work your way to referencing that value.
$data = array('blah1'=>array('blah2'=>array('hello'=>'world')));
$pathway = 'blah1/blah2/hello';
$pathway_parts = explode('/', $pathway);
$ref = &$data;
foreach ($pathway_parts as $part)
{
// Possibly check if $ref[$part] is set before doing this.
$ref = &$ref[$part];
}
$ref = 'value';
var_export($data);
this doesn't sound like the best structure, but something like this might work:
//$data = array('blah1'=>array('blah2'=>array('hello'=>'world')));
$pathway = 'blah1/blah2/hellow';
$pathway_parts = explode('/', $pathway);
$value = 'some value';
$data = $value;
while($path = array_pop($pathway_parts)){
$data = array($path=>$data);
}
echo '<pre>'.print_r($data,true).'</pre>';
Other than that, you might be able to build a json string and use json_decode on it. json_decode doesn't execute code.

PHP, problem with str_replace while reading from array

i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..
what i have done so far is this :
$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000,';');
$glossArray[$line_of_text[0]] = $line_of_text[1];
$counter++;
}
fclose($file_handle);
$file = file_get_contents("file2.html");
foreach($glossArray as $key => $value){
$results = str_replace($key," means ".$value ,$file);
}
echo $results;
i think that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged
any help would be appreciated
thank you in advance
Nader
P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.
Update: changing the foreach with :
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.
You're passing the entire $glossArray in to str_replace each time. You're also passing the initial file contents in each time you do str_replace, so at most you'd see one replacement. I think you want to change to something like this:
$results = $file;
foreach($glossArray as $index=>$value)
{
$results = str_replace($index,$value ,$results);
}
Since str_replace allows arrays for the first two parameters (as another user mentions) you could also do something like this instead of a loop:
$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);
Yes, the problem is in your second foreach. It should read like this:
foreach($glossArray as $key => $value){
$results = str_replace($key,$value ,$file);
}
You forgot the key, so it's replacing every instance of every value in $glossArray with the $value. Good luck with that!
Why are you opening file2.html for reading and writing, then grabbing the contents of it?
(BTW - this is going to go horribly wrong on a system with strict locking)
foreach($glossArray as $value)
{
$results = str_replace($glossArray,$value ,$file);
I think this should be
foreach($glossArray as $old=>$new)
{
$results = str_replace($old, $new, $file);
Although it would be a lot more efficient to load the pairs from the glossary into 2 seperate numbered arrays, then just call str_replace once.
Your first parameter for str_replace should not be $glossArray as that's an array and not the string to replace.
I assume that your CSV-file contains something like "SEARCH;REPLACE"? In that case, your foreach should look like this: foreach ($glossArray as $searchString => $value).
Then try
$file = str_replace($searchString, $value ,$file);
instead of
$results = str_replace($searchString, $value ,$file);
because right now you're overwriting $results again and again with every str_replace ... echo $file when you're done.
BTW: What's $counter doing?
The solution to your new problem (which should really be it's own question, not an edit of the existing one) is that array_values returns an array, and when you concatenate an array with a string, php inserts 'Array' instead of the value.
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
is incorrect. You should do this instead:
$vals = array_values($glossArray);
foreach($vals as $k=>$v)$vals[$k] = 'means '.$v;
$results = str_replace(array_keys($glossArray), $vals, $file);
Notice that the values of glossArray are extracted, and each value concatenated with your string - if you just try and concatenate the string with the array, you'll get a string, not an aray.

Categories