I am setting up a Jquery autosuggest using ajax and I have a simple query to the database which returns 5 suggestions. The fields are company and id, so I get
$result['id']
$result['company']
for each row of the returned database suggestiions
This works fine and currently I loop over the results
foreach ($result as $item) {
$suggest[] = $item['company'];
}
echo json_encode($suggest);
I want though to add these so the company is a label and id is a value, something like
"value": "A Company", "data": "20"
This I can then encode and use in my autosuggest.
Thanks in advance!
You have to save an array to main array like this
foreach ($result as $item) {
$suggest[] = [
'value' => $item['company'],
'data' => $item['id'],
]
}
echo json_encode($suggest);
And it should return something like this
[
{
'value': 'Some value',
'data' : item id
}
]
i will recommend you create an array, next create 2 more arrays as values for the value and data keys.
like this.
$arr=array();
$arr['value']=array();
$arr['data']=array();
while($suggest=mysql_fetch_assoc($result)){
array_push($arr['value'],$suggest['id']);
array_push($arr['data'],$suggest['company']);
}
echo "<pre>";
print_r($arr);
note that with this solution, if you delete an entry in either value or data
be ready to delete the corresponding entry in the other array.
others may be able to improve this or even offer a better approach.
Related
In this foreach, I use a function to pull the scores, I write the value I get from the foreach into the function.
foreach($surveys AS $s) {
$surList[$s->cat][] = ["id" => $s->id, "title" => $s->title, "score" => SurveyController::getScore($s->id),"subtitle" => SurveyController::getSubtitle($s->id,SurveyController::getScore($s->id)) ];
}
And in this function returns the message that corresponds to the score we got with case-when in the database
function getSubtitle($id,$score){
$surveys=DB::table("methodolgy")->where("main_survey",$id)->selectRaw("*, (CASE WHEN ".$score." BETWEEN start AND end THEN message ELSE 'bos' END) AS sonuc")->having("sonuc","!=","'bos'")->orderBy("id","ASC")->first();
return isset($surveys->message) ? $surveys->message : "Activity Not Found";
}
The problem is, when I try my query in SQL, the result is correct, but when I try it on my website, it always returns the first record in my methodolgy table.
I couldn't find why it does that.
Thanks for help.
This is because the foreach function always reads the aray and foreach data in the array it does something. For your case it is assigning data to a variable. You can create a variable like $allData and then append every data of the array to it. for example
$surList = [];
foreach($surveys AS $s) {
$oneData[$s->cat][] = ["id" => $s->id, "title" => $s->title, "score" => SurveyController::getScore($s->id),"subtitle" => SurveyController::getSubtitle($s->id,SurveyController::getScore($s->id)) ];
$surList.=$oneData;
}
I have a json file with this content :
[
{
"id": "apple",
"symbol": "app",
"name": "Apple",
},
]
I Want To Search In This Json File In id Or symbol Or name Columns,
I Write This Code :
$nameOrIDOrSymbol="apple"; // user types id or symbol or name.
$names= json_decode(file_get_contents("file.json", true), true);
$name_key1 = array_search($nameOrIDOrSymbol,array_column($names, 'id')
$name_key2 = array_search($nameOrIDOrSymbol,array_column($names, 'name');
$name_key3 = array_search($nameOrIDOrSymbol,array_column($names, 'symbol');
if($name_key1){
var_dump($name_key1);
}elseif($name_key2){
var_dump($name_key2);
}elseif($name_key3){
var_dump($name_key3);
}
How Can I Search In This Three 3 Array Columns Only Once With array_search Or Another Function? For example search like this :
$name_key = array_search($nameOrIDOrSymbol,array_column($names, 'id','name','symbol')
Currently you search first in the 'id' column, then in the 'name' column, and finally in the 'symbol' column. If, at any stage, you encounter a match you return the array key. If you want to keep this functionality you have to look through the columns in that order.
You could combine the three columns into one array, juggle a bit with the keys, and do a single search that way, but I don't think that's very efficient.
Why not restructure you code a bit? For instance like this:
$query = 'apple';
$columns = ['id', 'name', 'symbol'];
$data = json_decode(file_get_contents('file.json', true), true);
foreach ($columns as $column) {
$key = array_search($query, array_column($data, $column);
if ($key !== false) break;
}
var_dump($key);
Now you've only used array_search() once, in a way.
This code is more efficient than yours because it stops searching as soon as it has found 'apple' in a column. Your code always searches through all columns.
Note that I actually check that array_search() returns false, unlike what you did, which would not have responded when this functions returned key zero.
Also note that, if ever the need arises, you can now easily add more columns without having to add more repeating lines of code.
I have a function in my API to update the name of a person in an SQLite database. You give it the ID of the name you wish to change and the new name.
How can I build a function in a way that allows me to update a wide range of fields in the database? even things from different tables?
I started off trying to use parameters to switch which SQL query is executed, but this feels a bit clunky and not scalable. Is there a better way?
Current code:
private function json_update_authors() {
$input = json_decode(file_get_contents("php://input"));
$query = "UPDATE authors SET name = :name WHERE authorId = :authorId";
$params = ["name" => $input->name, "authorId" => $input->authorId];
$res = $this->recordset->getJSONRecordSet($query, $params);
return json_encode(array("status" => 200, "message" => "ok"));
}
Prependix
You can achieve what you want, but before reading the details, I recommend contemplating about what you would like to restrict this to, because if there is a file your function blindly trusts, then, should malicious input be inside that file, your database can easily be hacked. So, you should have a whitelist of tables/fields that you allow to be updated and apply that.
Decoding JSON
json_decode decodes your JSON into an object that you do not foresee its members. However, according to the documentation you can iterate this object like:
foreach ($obj as $key => $value) {
echo "$key => $value\n";
}
However, json_decode can decode your JSON into an array as well, like:
$input = json_decode(file_get_contents("php://input"), true);
I personally prefer to decode JSON into arrays, but you can operate with the first approach as well. In both cases, you can iterate the array in a similar manner as described above.
Recommended format
Your update has an anatomy as follows:
table
fields
filter
So, I would recommend that you could use a JSON representation of your input, that has a tableName field, which is a string, a fields field, which is an array of key-value pairs, the keys representing the fields to be updated and the values representing the values to update to and finally a filter field, which, if we intend to be very elegant, could also be an array of objects of key-value pairs, the keys representing the fields you are to filter by and the values representing the values you would filter with. A sample Javascript object that would comply to this format would look like the following:
[
{ //Your query
tableName: 'authors',
fields:
[
{
name: 'somename'
}
],
filters:
[
{
authorId: 123
}
]
},
{ //Some other example
tableName: 'books',
fields:
[
{
isbn: 'someisbn',
title: 'sometitle'
}
],
filters:
[
{
pageNumber: 123,
weight: '5kg'
}
]
},
]
I have given an example above, of two objects, so you can see that:
several updates can be notified in the JSON
you can update several fields in a single command
you can filter by several fields
I should mention that this is a rabbit hole, because you might want to vary the operator as well, but since this is a mere answer, I do not write a full elegant project for its purpose. Instead of that, let me just tell you that there is a lot of room for improvement, operator dynamicity springs to mind instantly as an improvement that you may need.
How to generate an update query:
//assuming that $JSON is a variable holding such values as describe in the previous chapter
foreach ($JSON as $obj) {
$tableName = $obj['tableName'];
$fields = [];
$filters = [];
$params = [];
$toExecute = isset($whiteList['tables'][$tableName]);
foreach ($obj['fields'] as $key => $value) {
$fields[]=($key.'=:field_value'.$key);
$params['field_value'.$key] = $value;
$toExecute = $toExecute && isset($whiteList['fields'][$key]);
}
foreach ($obj['filters'] as $key => $value) {
$filters[]=($key.'=:filter_value'.$key);
$params['filter_value'.$key] = $value;
$toExecute = $toExecute && isset($whiteList['filters'][$key]);
}
}
I have used a whitelist above to make sure that the queries will not update tables/fields using filters where the name of the table/field/filter is either badly formatted, malicious or unwanted. This code is untested, it might well contain typos, but the idea should be a good starting point.
I am using the Adobe Sign API and I need to map fields from a php array to the fields in a pdf document. I have managed to do it using the following json:
"mergeFieldInfo": [
{
"defaultValue": company['Trading Name'],
"fieldName": "Trading Name"
},
{
"defaultValue": company['Company Website'],
"fieldName": "Company Website"
}
]
The problem is I have 3 different pdf's all with 60+ fields. Is there anyway I could create this json structure by looping through the array? So far I have split the array in to two. One holds the default values and the other the field names not sure if thats the right way to be going
Solved using json_encode
foreach ($company as $key => $value){
$arr[] = ['defaultValue' => $value, 'fieldName' =>$key];
}
json = json_encode($arr);
Result:
{"defaultValue":"New Company","fieldName":"trade_name"},
{"defaultValue":"Website","fieldName":"website"}
Lets assume, the return value of an search-fuction is something like this
// If only one record is found
$value = [
'records' => [
'record' => ['some', 'Important', 'Information']
]
]
// If multiple records are found
$value = [
'records' => [
'record' => [
0 => ['some', 'important', 'information'],
1 => ['some', 'information', 'I dont care']
]
]
]
what woul'd be the best way to get the important information (in case of multiple records, it is always the first one)?
Should I check something like
if (array_values($value['record']['records'])[0] == 0){//do something};
But I guess, there is a way more elegant solution.
Edit:
And btw, this is not realy a duplicate of the refered question which only covers the multiple records.
If you want the first element of an array, you should use reset. This function sets the pointer to the first element and returns it.
$firstValue = reset($value['record']['records']);
Edit.. after reading your question again, it seems, you dont want the first element.
You rather want this
if (isset($value['record']['records'][0]) && is_array($value['record']['records'][0])) {
// multiple return values
} else {
// single return value
}
Doing this is kind of error proun and i wouldn't suggest that one function returns different kinds of array structures.
check like this..
if(is_array($value['records']['record'][0])) {
// multiple records
} else {
// single record
}