Mirror SQL's LIKE functionality for a PHP array? - php

At the minute I have a page with an AJAX script that searches a database with LIKE '%search term from input box%'.
I need to modify it so that instead of searching the database it searches an array (that has been constructed from two tables - I can't use a JOIN because there's a bit more to it than that).
How do I go about creating a fuzzy search function in PHP that will return all the possible matches from the array?

you want preg_grep
e.g.
$arr = array("tom jones", "tom smith", "bob jones", "jon smith");
$results = preg_grep("/jones/",$arr);
$results will now contain two elements, "tom jones" and "bob jones"

you could just loop over the array and use strpos to find the matching elements
foreach( $arr as $value ) {
if ( strpos($value, 'searchterm') !== FALSE ) {
// Match
}
}
You could use a regular expression for more advanced searching, but strpos will be faster if you are just trying to do a simple LIKE '%term%' type search.

Related

How can I best loop out this xpath expression from a comma separated list?

I have multiple 'PINs' as I'll call them, stored in a input field in a comma separated format. So these are stored as a string in the format '1234,5678'.
I can already get xPath to filter an XML file for a single value by using this:
xpath("/ReaderDetails/Reader[Pin=1234]")
I'm trying to find a simple way to take the comma separated string, and interpret into the xpath expression so I can use multiple values.
The intended outcome will be:
xpath("/ReaderDetails/Reader[Pin='1234' or Pin='5678']")
It's important, that this should be able to handle as many PINs as are entered in the input field.
So far I'm able to put the PINs into an array using array_map('trim', explode(',', get_option('dream_team_readers'))) but can't figure out how to create the expression as needed above.
You ought, perhaps, to be able to accomplish the desired string pattern like this#
# to emulate the array of PINS...
$pins=[ 1234,3245,5423,4353,64576,5675,2347,3453 ];
$tmp=[];
foreach( $pins as $pin )$tmp[]=sprintf( 'Pin="%d"', $pin );
$expr=sprintf( '/ReaderDetails/Reader[ %s ]', implode( ' or ', $tmp ) );
If you were to print the resultant $expr variable you would get:
/ReaderDetails/Reader[ Pin="1234" or Pin="3245" or Pin="5423" or Pin="4353" or Pin="64576" or Pin="5675" or Pin="2347" or Pin="3453" ]

Is it possible to do a reverse search replace on a string if you know the original pattern?

I currently have an existing PHP string template mechanism that does a very simple parameter substitution. It works great, so consider the following:
Template:
{"name" : "The Person is called {$name}", "comments": "These are comments: {$comments}."}
PHP Replace function:
function replaceVariables($string, $values) {
$string_processed = preg_replace_callback(
'~\{\$(.*?)\}~si',
function($match) use ($values)
{
return str_replace($match[0], isset($values[$match[1]]) ? $values[$match[1]] : $match[0], $match[0]);
},
$string);
return $string_processed;
}
So, running:
replaceVariables($myTemplate, ["name"=>"John", "comments"=>"Hello World"]);
replaceVariables($myTemplate, ["name"=>"Mary", "comments"=>"Another variation."]);
...works exactly as expected and produces the desired result. However, how about if I wanted to "reverse engineer" back to the input parameter array!
For example, suppose I no longer had access to the ["name"=>"John", "comments"=>"Hello World"] parameter array. However, I do have the template and the output json string. Can anyone think of a way to reconstitute the original input array?
Been thinking about this for ages and cannot think of an elegant way of doing it!
Any ideas?
Ta,
Jab

How to make a combined array of .json array's in PHP?

I'm trying to make a form with a bunch of questions which can be added to a radioBox, checkBox etc. I have made a .json file containing the questions and possible answers like this (this is just a small part of the file):
{
"questions": {
"0": {
"question":"How many products?",
"answers":["Less than 1000", "More than 1000", "More than 10000"],
"score":[1, 2, 3],
"info":"This is additional information for question 1"
}
,
"1":{
"question":"How many websites?",
"answers":["One", "Two", "Three"],
"score":[1, 2, 3],
"info":"This is additional information for question 2"
}
}
}
I use a class in which I have several functions to make array's which can be used on my regular .php page. I have made an array of questions using the following piece of code, which works:
$questions = [];
foreach($json['questions'] as $key => $value){
$this->questions[] = $value['question'];
}
Now I can just use question[0] to get the first question and question[1] for the second, which is really nice. What I am trying to do is create an array that contains all the answers per question so I can do something similar with the answers. Ideally, it would look something like this:
array:
arrayQuestion1Answers:
string: answer1
string: answer2
string: answer3
arrayQuestion2Answers:
string: answer1
string: answer2
string: answer3
That way I could do something like arrayQuestion1[0] to get the first answer from the first question, and arrayQuestion2[2] to get the third answer from the second question.
Thank you for reading my long (and possibly stupid) question, hope you can help!
Try this,
$json = '{
"questions": {
"0": {
"question":"How many products?","answers":["Less than 1000", "More than 1000", "More than 10000"],"score":[1, 2, 3],"info":"This is additional information for question 1"
}
,"1":{
"question":"How many websites?","answers":["One", "Two", "Three"],"score":[1, 2, 3],"info":"This is additional information for question 2"
}
}
}
';
$questions = json_decode($json,true);
$question = $questions['questions'];
foreach($question as $key => $que):
$answer['arrayQuestion'.$key.'Answers'] = $que['answers'];
endforeach;
echo '<pre>';
print_r($answer);
You say you already have functions to convert the JSOn to PHP arrays. Have you ever checked out json_decode()? It's a native PHP function to decode your JSON. It returns false on failure.
Furthermore: why are you indexing the objects in your questions object in your JSON? You might as well type:
{
"questions": [
{"somekey": "this_is_question_0"},
{"somekey": "this_is_question_1"}
]
}
That way they're automatically indexed.
To answer you actual question, if you use what I describe above, you can simply access a question's answers like this:
$questions = json_decode($json);
$answers_to_question_1 = $questions[0]['answers'] ?? []; // ?? [] means: if not set, make it an empty array. This is the null coalesce feature, available in PHP 7.0 and higher. See http://php.net/manual/en/migration70.new-features.php.

Expand an string based on values in an array in PHP

I would like to expand a string with one or more values which come from an array.
Desired result:
http://example.com/search/key=["Start", "USA", "Minneapolis"]&shift=false
Array:
array(2) {
[0]=>
string(8) "USA"
[1]=>
string(4) "Minneapolis"
}
PHP Code:
$myArr = ("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start",' .$myArr[0]. ']&shift=false';
Gives me this result: http://example.com/search/key=["Start", "USA"]&shift=false
How can I make it more dynamic so that more than one value can be added? I know I somehow have to use a foreach($myArr as $i){...} and concatenate the values via $string += but because my variable is in the middle of the string I'm kinda stuck with this approach.
Try the following:
$myArr = array("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start", "' . implode('", "', $myArr) . '"]&shift=false';
This will provide the expected output using implode.
Something isn't right here. You are trying to pass array data through a querystring but not in a valid array structure. This means you are either not using it as an array on the next script and you are going to having to chop and hack at it when the data gets there.
I'll make the assumption that you would like to clean up your process...
Declare an array of all of the data that you want to pass through the url's query string, then merge the new key values into that subarray. Finally, use http_build_query() to do ALL of the work of formatting/urlencoding everything then append that generated string after the ? in your url. This is THE clean, stable way to do it.
Code: (Demo)
$myArr = ["USA", "Minneapolis", "monkey=wren[h"];
$data = [
'key' => [
'Start'
],
'shift' => 'false'
];
$data['key'] = array_merge($data['key'], $myArr);
$url = 'http://example.com/search/?' . http_build_query($data);
echo "$url\n---\n";
echo urldecode($url);
Output:
http://example.com/search/?key%5B0%5D=Start&key%5B1%5D=USA&key%5B2%5D=Minneapolis&key%5B3%5D=monkey%3Dwren%5Bh&shift=false
---
http://example.com/search/?key[0]=Start&key[1]=USA&key[2]=Minneapolis&key[3]=monkey=wren[h&shift=false
*the decoded string is just to help you to visualize the output.
Then on your receiving page, you can simply and professionally access the $_GET['key'] and $_GET['shift'] data.
If you have a legitimate reason to use your original malformed syntax, I'd love to hear it. Otherwise, please use my method for the sake of clean, valid web development.

why do javascript libraries using json choose a [ { } , { } ] structure

I've been using a few javascript libraries, and I noticed that most of them take input in this form: [{"foo": "bar", "12": "true"}]
According to json.org:
So we are sending an object in an array.
So I have a two part question:
Part 1:
Why not just send an object or an array, which would seem simpler?
Part2:
What is the best way to create such a Json with Php?
Here is a working method, but I found it a bit ugly as it does not work out of the box with multi-dimensional arrays:
<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}
<?php $encoded = json_encode(array_values($object)); ?>
output:
[{"foo": "bar", "12": "true"}]
Because that's the logical way how to pass multiple objects. It's probably made to facilitate this:
[{"foo" : "bar", "12" : "true"}, {"foo" : "baz", "12" : "false"}]
Use the same logical structure in PHP:
echo json_encode(array(array("foo" => "bar", "12" => "true")));
An array is used as a convenient way to support multiple parameters. The first parameter, in this case, is an object.
Question one:
JSON is just a way of representing an object and/or and array as a string. If you have your array or object as a string, it is much easier to send it around to different places, like to the client's browser. Different languages handle arrays and objects in different ways. So if you had an array in php, for example, you can't send it to the client directly because it is in a format that only php understands. This is why JSON is useful. It is a method of converting an array or object to a string that lots of different languages understand.
Question two:
To output an array of objects like the above, you could do this:
<?php
//create a test array of objects
$testarray = array();
$testarray[] = json_decode('{"type":"apple", "number":4, "price":5}');
$testarray[] = json_decode('{"type":"orange", "number":3, "price":8}');
$testarray[] = json_decode('{"type":"banana", "number":8, "price":3}');
$testarray[] = json_decode('{"type":"coconut", "number":2, "price":9}');
$arraycount = count($testarray);
echo("[");
$i = 1;
foreach($testarray as $object)
{
echo(json_encode($object));
if($i !== $arraycount)
{
echo(",");
}
$i += 1;
}
echo("]");
?>
This will take an array of objects and loop over them. Before we loop over them, we output the opening square bracket.
Then, for each object in the array, we output it encoded to JSON plus a comma after each one. We count the number of iterations so that we don't output a comma at the end.

Categories