How to create cases as key value in PHP array? - php

I am facing some logical issue. I am fetching data via upi status table which look like as follows.
on controller file i am creating the following logic..
$this->load->model('localisation/upc_status');
$statusArray = $this->model_localisation_upc_status->getUPCStatuses();
$this->data['statuses'] = $statusArray;
foreach ($statusArray as $sa){
$c[] = array($sa['status_id'] => $sa['name']);
}
echo $c['8'];
i am unable to get the name in-stock. instead i am getting Array in-place of it.

Try This,
$c[$sa['status_id']] = $sa['name'];
If you still can't get, adjust levels of the array.
Use print_r(array) to check arrays at required debugging points.

Related

How to put mutual followers/followings at top of the array when calling get followers/following api?

I'm calling a get API for a list of followers of another user, I want to put the users who I already follow on top of the list. How can I do that efficiently in laravel
this is how I have done it,
$user_details = User::with('followings:name,username,about_me,photo_url,leader_id as id')->where('id', $userId)->select('id')->first();
$my_details = User::with('followings:leader_id as id')->where('id', $request->logged_in_user->id)->select('id')->first()->toArray();
$ids = array_column($my_details['followings'], 'id');
$sortedfollowings = [];
foreach ($followings as $key => $value) {
if(in_array($value->id, $ids)){
array_unshift($sortedfollowings, $value);
} else {
array_push($sortedfollowings, $value);
}
}
I'm sorting list using foreach and if else, but it's not efficient when the list is like million followers.
This is more of an algorithm type of issue. This also depends on if you're using a package or not. Being this said, and not that much information provided and/or examples of what you've tried, I'll proceed explaining the process:
1.- A foreach loop that checks through your followings.
2.- Inside that loop, you add a conditional (if) that checks if any of your followings follow the id of the user profile you're visiting.
3.- Add into an array the users that follow that account.
4.- Send that array separately to your front-end.
5.- Merge that array in the beginning of the whole fetch.
6.- Exclude duplicates.
Again, I don't know which front-end you're using. I don't have any sample code, so I just proceeded with an explanation of how it can work.
This is a matter of loops and array manipulation.

How do i add fabricjs-canvas objects in json format to a indexed array in php?

I'm trying to make a database system to handle the saved fabricjs canvases. For every thing to work i need the canvas objects
json=canvas.toDatalessJSON; // in javascript
...to be saved in php as .json file in a indexed array system that allows me to load and add more canvas objects or delete objects.
The thing troubling me is how to actually structuring this. What i'm trying here is something like:
... The json structure i'm considering ...
["1"]{Object:.....}
["2"]{Object:.....}
["4"]{Object:.....} (["3"] deleted in this case)
... Trying to create in php ...
$i="1";
$A=[];
$A[$i]=[];
array_push($A[$i],json_decode($json));
$newjson=json_encode($A);
But this is obviously not the way to make it. Any ideas ?
EDIT 1
Thank's for your answer #Michael. I ended up not using exactly what you propose. But i accept it as the answer that let my to a solution. In my solution i'm adding the index to the object, and unset the index when i'm going to use the object.
Create:
$dataA=array();
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);
Add:
$data0=file_get_contents($filename.'.json');
$dataA=json_decode($data0,true);
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);
Assuming you are trying to overwrite element "1" in your json object using php, try this:
$newjson = json_decode($json, true);
$newjson["1"] = Array();
$newjson = json_encode($newjson);
If you want to add an element:
$newjson = json_decode($json, true);
$newjson[] = Array();
$newjson = json_encode($newjson);

Assign variable to an array from Active Directory

I am having trouble figuring out how to correct an issue I am having with the following code. I am trying to list the names and emails of all the people in my Active Directory. This code works. However, I also get the following warning when it is executed.
Warning: Cannot use a scalar value as an array.
From what I have read online I need to set " $name['mail']['0'] = "Not Found";" to an array. My question is how would I go about doing this. I have tried every way I could think of with no success. If anyone could provide me with some feedback it would be greatly appreciated.
foreach ($results as $name) {
if (!isset($name['mail']['0'])){
$name['mail']['0'] = "Not Found";
}
$allnames[$name['cn']['0']]['mail'] = $name['mail']['0'];
It looks like you are trying to assign the "Not Found" value BACK into the results of the ldap query you are running.
When I wrote code to get user information from ldap, I always inserted values into a different array (getting the fields I wanted) and then displayed THAT array out in the HTML:
foreach ($results as $name)
{
if (isset($name['mail']['0']))
// Check if it IS set, rather than not set and then append the data.
{
$allnames[$name['cn']['0']]['mail'] = $name['mail']['0'];
}
}
Then after you have all the fields you want you display the $allnames array.
Having said that, when I construct the array of user information, I make the array much much simpler - knowing what I want to display out, more along the lines of this:
foreach ($results as $name)
{
if (isset($name['mail']['0']))
// Check if it IS set, rather than not set and then append the data.
{
$allnames['mail'] = $name['mail']['0'];
}
}
You (or at least I) don't need to follow the ldap structure when making the array of information I have gathered, but rather I want to get specific fields from the directory and then display them by what they are - for example when I output the value in mail I might want to hyperlink it as an email address, so I keep it in an array element that I know by key and refer to later.

how to store values to array from mysql database in php

The following is my scenario
i have the following databases
employee(e_no,e_name,e_contact,e_mail)
project(p_no,e_no,p_name)
project_assigned(id,pno,eno)
task(id,pno,tasks)
Now I have two particular files called employee_data_sheet.php and addtask.php
I want to accomplish the following:
When I post a task to addtask.php I want to view which employee has got the task in which project in employee_data_sheet.php
Following is the code snippet:
(my addtask.php is working fine error in employee_data_sheet)
$query34="SELECT p_no FROM project_assign WHERE e_no='$empno'";
$res34= mysql_query($query34);
while($row34= mysql_fetch_array($res34))
{
$pnum=array();
$pnum=$row34['p_no'];
$query35="SELECT p_name FROM project WHERE p_no='$pnum'";
$res35=mysql_query($query35);
while($row35= mysql_fetch_array($res35))
{
$prname1=array();
$prname1=$row35['p_name'];
}
}
The problem is that I am not able to store the result of query to an array with comma separation.
Please help me to store the result of a query to an array with comma separation
You are using deprecated database access functions. However I believe you are trying to do this
$prname1=array();
while($row35= mysql_fetch_array($res35))
{
$prname1[]=$row35['p_name'];
}
$string = implode(",", $prname1);

Importing post data into an array

I have a page "bottom1.php" it has 16 select menus, labled rating1-rating16.
When the user submits this form, the next page has a script that looks like this:
//pulling data from post into array.
import_request_variables("p", "form_");
$scores= array($form_rating1,$form_rating2,$form_rating3,$form_rating4,$form_rating5,$form_rating6,$form_rating7,$form_rating8,$form_rating9,$form_rating10,$form_rating11,$form_rating12,$form_rating13,$form_rating14,$form_rating15,$form_rating16);
//putting array into session
$_SESSION['scores']=$scores;
the user is then directed to another page where an additional 16 selections are made, then the same script is ran, only this time the array is stored into the session as "scores2".
The user is shown the output from each array, and then when the user confirms that the values are correct, each member of the scores, and scores2 array is parsed out, put into another variable, and then inserted into a database.
I know this is a primitive way of accomplishing this, but its the only way I know how.
This method worked with php configuration of 5.2.13, but I switched to a server with a configuration of 5.1.6 and now this script wont work. This script is critical to my site. Thanks for your help!
The parsing script looks like this:
$fpage=$_SESSION['scores'];
$spage=$_SESSION['scores2'];
$score1 = $fpage['0'];
$score2 = $fpage['1'];
$score3 = $fpage['2'];
$score4 = $fpage['3'];
$score5 = $fpage['4'];
...
$score31 =$spage['13'];
$score32 =$spage['14'];
$score33 =$spage['15'];
And then I insert $score1 - $score33 into my db..
The way you are doing it isn't exactly safe, for the same reason register_globals() is/was a bad idea. If you happen to prefix one of your internal variables with 'form_', the user could overwrite that value and potentially inject harmful code (depending on how that variable is used).
A better way to do this would be to filter the array directly into a new array using array_filter() or preg_grep().
Oliver A.'s solution only works in the scenario that all of the array keys will be in the form of 'form_rating', but your original script assumed a prefix of 'form_'.
preg_grep could be used as follows:
$keys = preg_grep('/^form_/', array_keys($_POST));
$scores = array();
foreach ($keys as $key) {
$scores[$key] = $_POST[$key];
}
I do not have a php enviroment to test this right now but this should work:
$scores = array();
for($i=1;array_key_exists("form_rating{$i}",$_POST);$i++){
$scores[] = $_POST["form_rating{$i}"];
}
EDIT: I tested and working
If the script does not work when PHP changes version then:
Check the logs to see the errors
Check the PHP Changelog for any function or control structure change that my halt your script.
Just an issue that it happen to me a lot when switching between 5.1 and 5.2 is the Elvis operator ?: which is not recognized in php 5.1.
This is why is important to develop on the same kind of configuration that the server has, or to implement unit-testing and automatic deployments which can detect this problems before reaching production.

Categories