Convert an array of arrays in Vue.js - javascript

How can I convert an array of arrays to a single array in Vue.js? In my php back-end, I have the code below that fetch data from database. My problem now is I don't know how to convert them in my js side to a single array.
PHP side:
$name = DB::raw("CONCAT(emp.first_name, ' ', emp.last_name) AS name");
$nameCol = [];
$usedDate = '2018-07';
$date = 'attendance.date';
$total = 'attendance.total';
for($i = 1; $i<32; $i++){
if($i<10) $i = '0'.$i;
$names = DB::table('attendance')
->leftJoin('m_emp','m_emp.emp_key','=','attendance.emp_key')
->select($name,$date,$total)
->where(DB::raw("(DATE_FORMAT(attendance.date,'%Y-%m-%d'))"), '=', $usedDate.'-'.$i)
->get();
array_push($nameCol,$names);
}
return (array)$nameCol;
Result is like this:
Inside of each array is like this:
And finally inside it is this:
Can I do for loop on it to transform it to a single array and how? Or can I right away search for an item inside it? Because I have tried search using a way like this but I think this only search or works in a single array (that's my reason why I want to merge them to one array):
Vue.js side
list.find( empName=> empName.name === 'John Doe')
//let's assume list is the variable that receives data returned from php
//result for this one is undefined.
Any idea how ?

You can use array_merge instead of array_push.
I guess you are using Laravel , you have to convert the collection to array before merging that, see the example :
$name = DB::raw("CONCAT(emp.first_name, ' ', emp.last_name) AS name");
$nameCol = [];
$usedDate = '2018-07';
$date = 'attendance.date';
$total = 'attendance.total';
for($i = 1; $i<32; $i++){
if($i<10) $i = '0'.$i;
$names = DB::table('attendance')
->leftJoin('m_emp','m_emp.emp_key','=','attendance.emp_key')
->select($name,$date,$total)
->where(DB::raw("(DATE_FORMAT(attendance.date,'%Y-%m-%d'))"), '=', $usedDate.'-'.$i)
->get();
// use array_merge
$nameCol = array_merge($nameCol,$names->toArray());
}
return (array)$nameCol;

Related

How to solve "notice array to string conversion in C" error in php and javascript?

So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?

Returning values from single column with mysql queries

I have a php function that will get a list of name from column in users database. What I want to do is to get all the values from the column name and insert it into an array.
What I've done from the php side is :
header('Content-type: application/json');
include ('../Core/Initialization.php');
$courseName = $_POST['courseName'];
$semester = $_POST['semester'];
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$column = mysql_fetch_assoc($sql);
$arr = array();
foreach($column as $value) {
$arr[] = array('name' => $value['name']); //I have tried it this way but it didn't work when I try to display the values.
}
echo json_encode($arr);//I have tried to remove the array and just json_encode($column). I have successfully print out the first values, but fail to print out the next values collected from the column.
The js function that will process/print out the name:
function nameProcess(data) {
alert(data.name); //This will only display the full values from the first(?) index
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i]); //But, this loop only displays one character each time of the alert. Example: Each character from the word "Hello" will show up one by one as alert.
}
}
});
Is there any better way to do this? What I want to do is, exporting all values from column name into an array, and iterate each of its value as an option of a a select box. But for now, how do I fix the problem?
First of all, don't use mysql_* functions as they are deprecated and
removed totally PHP 7.
Back to your question, you can fetch mysql multi-dimensional array with MySQL only with loop.
Corrected code:
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$res = mysql_query($sql); // Missing this.
$column = ;
$arr = array();
while ($value = mysql_fetch_assoc($res)) {
$arr[] = $value['name'];
}
echo json_encode($arr);
Note: The PHP MySQL commands you are using are deprecated. It's recommended to use the PDO class (as MySQLi is also deprecated).
It depends on the pre-processing you are performing, but from what I can see based on the information you provided, you are passing each element of the returned data through to nameProcess.
So a return data of
array(
array('name' => 'John Smith',
array('name' => 'Jane Doe',
array('name' => 'Foo Bar'
);
Will require the nameProcess function to be invoked 3 times.
So each time you go through to define
nameArray = data.name;
nameArray becomes a string since data.name is 'John Smith' the first invoke, 'Jane Doe' the second invoke, and 'Foo Bar' the last invoke.
So when you call
alert(nameArray[i]);
It's calling the character at position i within the string.
nameArray[0]; // 'J'
nameArray[1]; // 'o'
nameArray[2]; // 'h'
nameArray[3]; // 'n'
// etc
If you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
alert(nameArray);
}
It will alert the full name.
The way around this would be to ensure that you pass the JSON parsed data to the function without the pre-processing, in which case your original code should work if you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i].name);
}
}

How do I differentiate array values from PHP in Ajax success function?

I am echoing two array values from PHP. How do I differentiate these values in ajax.
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$i]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$i]['firstname'] = $row1['firstname'];
$traineravaildetails[$i]['lastname'] = $row1['lastname'];
$traineravaildetails[$i]['emailidvalue'] = $row1['email_id'];
$i++;
}
echo json_encode($trainerdetails);
echo json_encode($traineravaildetails);
}
?>
function loadavailabletrainers (m) {
$.ajax({
url: 'assignavailtrainers.php',
data: { action:'test' },
type: 'post',
success: function(output) {
console.log(output);
}
});
}
I've seen a examples of multiple return values from php and handling them in ajax, but I didn't understand them. Can someone please explain how to differentiate output values in my case?
OUTPUT:
[[{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"2","idi":"2"}],{"7":{"facilitatorid":"1","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*******#gmail.com"},"8":{"facilitatorid":"2","firstname":"Vignesh","lastname":"Anandakumar","emailidvalue":"vign*****#gmail.com"},"9":{"facilitatorid":"3","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*****#hotmail.com"},"10":{"facilitatorid":"4","firstname":"Vignesh","lastname":"Anand","emailidvalue":"****#live.com"}}]
It's a nice practice to send only one stream of values so you can process it all at once.
First, you could create a container array:
$data = array('trainerdetails' => $trainerdetails,
'traineravaildetails' => $traineravaildetails);
Then
echo json_enconde($data);
This will generate a merged output.
The encoded string returned by your PHP code needs to be decoded in the client side (more details: Parse JSON in JavaScript?). Because of that, you could use $.getJSON(), which is an alias for a specific call to $.ajax (doc: http://api.jquery.com/jquery.getjson/).
The 'success' function will pass a 'key'=>'value' array data. In this case you'd need to treat the value as they may contain extra levels of arrays. It helps if you can visualize your data structure as tree view, like this: http://jsonviewer.stack.hu/ (paste your output there).
I hope it helps!

Retrieve data from PHP file using $.getJSON

I'm trying to set up a comments system on photos.
I understand how to use $.getJSON when the array is like this:
get.php:
$var = 5;
echo json_encode(array('var'=>$var));
main.php:
$.getJSON("get.php",function(data){
number = data.var; // number = 5
});
But I have a more complex thing.
My comments table has these 4 columns: id | photo_id | comment | date
For example let's say we're trying to retrieve the comment data from the photo with
photo_id == 1.
We don't know how many comments there might be.
In getcomments.php:
$photoid = 1;
$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");
while($commentrow = $comment->fetch_assoc()) {
$comments[] = $commentrow;
}
Then you encode it:
echo json_encode($comments);
Which prints something like this (the photo has 2 comments):
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
How do I declare variables for the comments array?
$.getJSON("getcomments.php",function(data){
// how do I declare variables for the comments array, especially since you don't know how many there might be?
});
Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.
If you want to display the comments you need to loop over the array. You can use for loop or forEach function.
$.getJSON("getcomments.php",function(data){
data.forEach(function(comment) {
$('div').append('<span>' + comment.comment + '</span>');
});
});
To display two JSONs you need to combine them into one JSON object.
echo json_encode(array('img' => $img1link, 'comments' => $comments));
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
Using this JSON, data is an array and you should manage it as an array. You can loop through it using simple loops (for, while...) or using new functional methods like forEach, map, filter....
Please try with this example:
$.getJSON("getcomments.php",function(data){
data.forEach(function(item, index, all) {
console.log(item.comment);
});
});
Declare an object, and push it to the array.
var commentsArr = [];
for (var i = 0; i < data.length; i++) {
var objToPush = {
id: data.id,
comment: data.comment,
date: data.date
}
commentsArr.push(objToPush);
}

Slice a JSON string

I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.

Categories