following problem: I want to build a mysql based language system.
To decrease loading time and increase performance I thought it would be the best, to first fetch all Language phrases into an array (which happens with mysqli fetch array). Then, if a language term is required, calling a function with the array as global variable.
My function for the array:
$sql = $db->query('SELECT * FROM lang_phrases WHERE phraseLanguageId = 1');
$phrases = array();
while($row = $sql->fetch_array()) {
$phrases[] = $row;
}
Now I've got this array:
array(2) {
[0]=> array(8) {
[0]=> string(1) "1"
["phraseId"]=> string(1) "1"
[1]=> string(1) "1"
["phraseLanguageId"]=> string(1) "1"
[2]=> string(4) "HOME"
["phraseKey"]=> string(4) "HOME"
[3]=> string(10) "Homepage"
["phraseContent"]=> string(10) "Homepage"
}
[1]=> array(8) {
[0]=> string(1) "2"
["phraseId"]=> string(1) "2"
[1]=> string(1) "1"
["phraseLanguageId"]=> string(1) "1"
[2]=> string(4) "BACK"
["phraseKey"]=> string(4) "BACK"
[3]=> string(6) "Back"
["phraseContent"]=> string(6) "Back"
}
}
And thats my function:
function l($key) {
global $phrases;
return PLACEHOLDER;
}
I wonder, how can I now search the array for "phraseKey" $key from the function and get the value?
Do you have any hints? Or shall I simply select each phrase with each one query (performance problems with 100 quers per load?!)?
Cheers and Thanks!
That's a bad structure. Why not key your array with the phrase ID and the language? e.g.
$translations = array(
'HOME' => array(
'english' => 'Home',
'french' => 'Maison',
'german' => 'Haus"
etc...
This eliminates the need for ANY searching. You just look up directly by language/phrase ID.
May I suggest to retrive the phrases with
while($row = $sql->fetch_array()) {
$phrases[$row['phraseKey']] = $row;
}
Then in your function l($key) you can search them with
$t = isset($phrases[$key]) ? $phrases[$key] : null
Related
I am new at php. Maybe a simple question.. I want to make parent->child view. I have an array like this:
With key id and key parent.
How to draw in cycle correct structure? Maybe at first I need to create function for creating the tree ?
-Apple
-Services
Duster
array(3) {
[0]=>
array(6) {
["id"]=>
string(3) "127"
["title"]=>
string(5) "Apple"
["deleted"]=>
string(1) "0"
["parent"]=>
NULL
["usp_id"]=>
string(3) "445"
["user_id"]=>
NULL
}
[1]=>
array(6) {
["id"]=>
string(3) "159"
["title"]=>
string(14) "Renault Duster"
["deleted"]=>
string(1) "0"
["parent"]=>
NULL
["usp_id"]=>
string(3) "495"
["user_id"]=>
NULL
}
[2]=>
array(6) {
["id"]=>
string(1) "7"
["title"]=>
string(8) "Services"
["deleted"]=>
string(1) "0"
["parent"]=>
string(3) "127"
["usp_id"]=>
string(2) "79"
["user_id"]=>
string(3) "275"
}
}
Cycle through the source array $arr to detect records that have a parent (not null). When a child record is found, push it into the parent.
foreach ($arr as $key0 => $record) {
if (null !== $record['parent']) {
foreach ($arr as $key1 => $parent) {
if ($parent['id'] === $record['parent']) {
$arr[$key1]['children'][] = $record; // push child into parent
unset($arr[$key0]); // delete child
}
}
}
}
demo
A simple and common idea is to prepare your data for easy printing. In your case, you need to group your data so that each item includes parent and children data.
Create a temporary array ($temp). Each item would be something like this:
['id' =>, 'name' => '', children => ['name' => '']]
And iterate through your original array ($curr) two times.
First pass:
parent is not null:
$temp[$curr['parent']]['children'][] = ['name' => $curr['name']]
parent is null:
$temp[$curr['id']] = ['name' => $curr['name'], 'children' => []]
In the second pass simply print it since you already have everything grouped.
I'm getting confused about how to insert array into array and give it a key name. Not number!.
I have the main array, which contains info about customer. the sub array should be called ["verlauf"].
The ["verlauf"] array conatins multiple arrays ( as same as db row count ). the main idea is that the sub array should be having the key name ["verlauf"]. in my code im getting the [0] as key.
Current array output:
array(19) {
["id"]=> string(1) "1"
["name"]=> string(11) "qwert zuiop"
["email"]=> string(23) "xy#gmail.com"
["phn_num"]=> string(12) "123456789"
[0]=> array(1) {
[0]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "22:25"
["status"]=> string(1) "0"
["info"]=> string(34) "some info"
}
[1]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "23:25"
["status"]=> string(1) "1"
["info"]=> string(34) "some info"
}
}
}
what i want is that the [0] on line 6 in the above example to be ["verlauf"]
My PHP:
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
array_push($returnArray, $verlaufArray);
Please note that $returnArray is the "main array".
You can simply do that by using associate array-
Your PHP code -
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
$returnArray['verlauf'] = $verlaufArray;
There's no need to complicate things so much. It looks like you need just one line of code.
$returnArray['verlauf'] = $result->fetch_all(MYSQLI_ASSOC);
There's no need for the while loop if the structure remains the same. fetch_all(MYSQLI_ASSOC) will give you an array containing associative results from your query.
Edited
I get the combined item_ids now, but not the single item_ids.
I have an array with three keys.
$searchArray = {
[0]=> array(3) {
["keyword"]=> string(7) "history"
["url"]=> string(7) "history"
["item_id"]=> string(2) "16"
}
[1]=> array(3) {
["keyword"]=> string(4) "past"
["url"]=> string(4) "past"
["item_id"]=> string(2) "16"
}
[89]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "34"
}
[93]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "35"
}
I want to combine the options that have the same keyword/url.
Just need to check if keyword matches.
The final format needs to be something that jquery autocomplete can accept, where I can assign the text to keyword and the value to url, id to the item_id.
There were only two keys in the array before and I would combine matches this way.
foreach ($searchArray as $row)
{
$combineMatches[ $row['keyword'] ][] = $row['item_id'];
}
result after using json_encode():
"anthropologist":["27","37"],
"biomedical":["34","35"],
"m.s.":["18","19","23"]
What I currently have:
$combineMatches = array();
foreach ($searchArray as $row)
{
$match =
array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id']+= $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array_push($row['item_id'])
]);
}
}
Result:
[7]=> array(3)
{
["keyword"]=> string(8) "theology"
["url"]=> string(8) "theology"
["item_id"]=> NULL
}
[13]=> array(3)
{
["keyword"]=> string(7) "writing"
["url"]=> string(7) "writing"
["item_id"]=> NULL
}
How do I add to the array column of just item_id ? Which I see is a string, but I need as an array.
This gets JSON encoded in the end of the PHP and read by jquery autocomplete.
Thank you for pointing out the string/array issue.
I changed how to add to the third key if there is a match, and if there isn't a match the solution was changing the array_push to just array.
$combineMatches = array();
foreach ($searchArray as $row)
{
$match=array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id'][] = $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array($row['item_id'])
]);
}
}
I am trying to loop through array of arrays in php. Usually get stalked with complex array sometimes but I need your kind assistance with this.
var_dump($array) produced the array below:
$arrayVal = array(6) {
["item_id"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
["request_explanation"]=>
array(2) {
[0]=>
string(7) "Welcome"
[1]=>
string(11) "Hello World"
}
["quantity"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "4"
}
["unit_cost"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "3"
}
["total_cost"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["supporting_document"]=>
string(0) ""
}
My database table:
I want to be able to save each of the value in that array into the table above. Thanks for helping me.
Use the indexes of one of the sub-arrays to access all the other sub-arrays:
foreach ($array['item_id'] as $i => $item_id) {
$request_explanation = $array['request_explanation'][$i];
$quantity = $array['quantity'][$i];
// repeat this for all the columns
// Now you can insert all these variables into the database
}
Use a loop to build 2 separate arrays:
foreach($array['ExpensesList'] as $index => $val){
$array1[$index] = $array['ExpensesList'][$index][0];
$array2[$index] = $array['ExpensesList'][$index][1];
}
Then insert each array into your database individually.
This will not work if any sub array contains an index at 2, so this is explicitly for the example structure you provided.
First sorry, i am only developing in php for a month and i do not know how to update this with laravel
I would like to update multiple photos.
Photos have a title description, etc.
My problem is i have no clue how to do it.
I tried the following
public function update(Request $request, Photo $photo)
{
// loop through array of id's
foreach ($request->photo_id as $id)
{
// find
$photos = $photo->find($id);
// loop throug input fields
foreach ($request->except('_token', 'tags', 'photo_id') as $key => $value)
{
$photos->$key = $value;
$photos->save();
}
}
die();
}
I get the following error
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
So i figured out the problem is with the value
And the results are like this
Key variable
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
Value variable results
array(2) {
[0]=>
string(9) "title one"
[1]=>
string(9) "title two"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(0) ""
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
I tried several other attempts but nothing works
Could please someone help me out with this?
Without knowing more about what is passing you the request object, I can't really go into specifics but you probably want to get your request object to look something like this:
'photos' => [
{
'id' => 1,
'title' => 'title one',
// more properties ....
},
{
'id' => 2,
'title' => 'title two',
// more properties ....
},
]
Then try something like this:
public function update(Request $request)
{
// Loop through the request photo id's
$request->photos->each(function($photo) use ($request) {
// Return the photo object you want to update
$photo = Photo::find($photo->id);
// Get the things you want from the request and update the object
$photo->title= $request[$photo_id]->title;
// Save the object
$photo->save();
})
}
You also may want to try out the dd(); function instead of die();. It makes debugging a lot easier.
I think, Photo Model missed the fillable array.
protected $fillable = ['var1', 'var2', ...];