Splicing an element in the middle of an associative array - php

I want to add elements to arrays within an object that I access like this to retrieve data.
var event_id = events_data.event_id[i]["0"];
var event_title = events_data.event_title[i]["0"];
var selected_source = events_data.selected_source[i]["0"];
var channel_id = events_data.channel_id[i]["0"];
events_data is an object with elements event_id, event_title, ... That object is created in a php function like this.
$return = array();
$return['event_id'] = $event_id;
$return['event_title'] = $event_title;
$return['selected_source'] = $selected_source;
$return['channel_id'] = $channel_id;
$return['channel_name'] = $channel_name;
$return['event_site'] = $event_site;
$return['event_url'] = $event_url;
$return['start_date'] = $start_date;
$return['start_time'] = $start_time;
$return['end_date'] = $end_date;
$return['end_time'] = $end_time;
$return['event_notes'] = $event_notes;
echo json_encode($return);
EDIT - ADDED INFO
The json object looks like this.
{"event_id":[{"0":"e20120319215556"},{"0":"e20120310221512"},{"0":"e20120319151903"},{"0":"e20120309123705"},{"0":"e20120307122044"},{"0":"e20120306182514"},{"0":"e20120309211714"},{"0":"e20120314130727"},{"0":"e20120319150532"},{"0":"e20120319141928"},{"0":"e20120319141201"},{"0":"e20120301193226"},{"0":"e20120301184354"}]}
END INFO ADDED
On the javascript side I get the events_data array like this.
$.ajax({
url: "get_events_data.php",
type: "POST",
dataType : 'json',
data: { },
cache: false,
async: false,
success: function (rdata) {
events_data = rdata;
}
});
To add an element to events_data on the javascript side, I check for the index where to add the new element and then add it with splice. But since the data is retrieved with the ["0"] text key for the associative array, I don't know how to specify the splice parameters.
for ( var n=0; n<events_data.event_id.length; n++ ) {
if ( current_event_id == events_data.event_id[n]["0"] ) {
//splice_index = n;
events_data.event_id.splice(n,0,event_id);
events_data.event_title.splice(n,0,event_title);
events_data.selected_source.splice(n,0,selected_source);
events_data.channel_id.splice(n,0,channel_id);
events_data.channel_name.splice(n,0,channel_text);
events_data.event_site.splice(n,0,event_site);
events_data.event_url.splice(n,0,event_url);
events_data.start_date.splice(n,0,start_date_string);
events_data.start_time.splice(n,0,start_time_string);
events_data.end_date.splice(n,0,end_date_string);
events_data.end_time.splice(n,0,end_time_string);
events_data.event_notes.splice(n,0,event_notes);
break;
}
}
Specifying the splice index "n" doesn't seem to do it. What should I change?
Thanks.

Answer was quite simple:
Adding an object to an array of objects with splice
var add_object = {"0",event_id}; // declare event id as object
events_data.event_id.splice(n,0,add_object); // splice object into object array at index

Related

Get multiple filter value parameters

I'm using this SO question to handle my filter search using checkbox.
This is the JS
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
// get all keys.
var keys = Object.keys(data);
var fdata = "";
// iterate over them and create the fdata
keys.forEach(function(key,i){
if (i>0) fdata += '&'; // if its not the first key add &
fdata += key+"="+data[key].join(',');
});
$.ajax({
type: "get",
url: "/ajax/get",
data: {
"_token": "{{ csrf_token() }}",
"fdata": fdata
},
success: function (response) {
$('#d2d-results').html(response);
}
});
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
And now I try to get the value of fdata to PHP.
On PHP I get this value of variable echo $_GET['fdata'];:
discount=Y&brand=BR0006,BR0003
What I want
$discount="Y";
$brand="BR0006,BR0003";
Is it possible to do like that?
To do what you want, you have to do two steps:
parse the query string into an array:
parse_str($_GET['fdata'], $result);
And then, extract the array as variables:
extract($result);
A few things to note:
Using extract is very insecure (and somewhat ugly). The user can put things like (for example) isAdmin=1 in the URL and the will affect your code. Basically, you cannot trust your variables anymore.
I would skip step 2 (the extract thingy), and use $result directly, for example echo $result['discount'].
it sounds like you are mixing post and get, is it something like this that you're after?
via GET:
if(isset($_GET['discount'])) {
$discount = $_GET['discount'];
} else {
$discount = '';
}
if(isset($_GET['brand'])) {
$brand = $_GET['brand'];
} else {
$brand = '';
}
POST method:
if(isset($_POST['discount'])) {
$discount = $_POST['discount'];
} else {
$discount = '';
}
if(isset($_POST['brand'])) {
$brand = $_POST['brand'];
} else {
$brand = '';
}
in one way , you can use explode function in php to separate your item from fdata
you can define some character in your client JS app for example ( , ) and then in explode function in php you must set separator equal comma character
explode function in PHP
explode(separator,string,limit)
in your example separator is comma and string is fdata ( limit optional
)
$fdata = $_GET['fdata'];
$arr_ = explode('&',$fdata);
and if you have some thing like this in fdata string
para1=223&para2=4353&para3=234
then $arr_ variable like this
$arr_ = [para1=223 , para2=4353 , para3=234];
and if you want separate value and key , you can do this again and use loop

looping through multiple arrays in JQuery from a multi array JSON response

Am I on the wrong path here?
I have a ajax call to upload some files.
I then create a array on the PHP side and send it back as JSON. But im not sure if the JSON format is correct.
Problem is I want to populate a dataTable with the returned JSON data, but I having difficulty reading the data. If its a single file then its fine and it works, but as soon as its more than one file
PHP CODE
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
$json = array();
$json[] = $row;
echo json_encode($json);
on the JQuery/AJAX call side
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: './inc/MediaScripts.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(html) {
var t = $('#vidlib_dtable').DataTable();
var obj = eval(html);
$.each(obj, function(key,value) {
t.row.add( [
value.name,
value.title,
value.path,
value.duration,
value.uploaded_date,
value.uploaded_by,
value.keyword,
value.comment,
] ).draw();
});
});
});
});
The original return has more columns, hence the above columns in the dataTable add.
The return looks like multiple (singular) JSON arrays.
[{"uuid":"236","name":"Koala.jpg"}]
[{"uuid":"237","name":"Lighthouse.jpg"}]
I was wondering if it should not take the shape of something like this
[{"uuid":"236","name":"Koala.jpg"}, {"uuid":"237","name":"Lighthouse.jpg"}]
If the format that I receive the data in is fine, how do I go about looping trhough the multiple arrays on the JQuery side?
That's because you are echo'ing 3 different JSON object arrays.
Each time your loop iterates you echo, the loop then re-creates the array and echo's the new JSON array.
$json = array();
//forloop{ START
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
array_push($json, $row);
//} END
echo json_encode($json);
Initialize your array before the loop, and echo it after it's been fully created.

How to create a two-dimensional array in PHP and iterate through it with Javascript

Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});

AJAX POST two dimensional array to a Zend controller and recieving it

Hi in my view I am creating a two dimentional array in javascript and passting it to the update controller as follows :
Array in Javascript
item[0][0] = null;
item[0][1] = 1;
item[1][0] = 2;
item[1][0] = 3;
alert (item); will show ,1,2,3
Passing it to Zend controller as :
$.ajax({
type: "POST",
url: "admin/navigation/update",
data: item,
success: function(data) {
alert(data);
},
error: function() {
alert("failure");
}
});
return false;
}
How can I receive this from update controller and assign to it a php array as
public function updateAction() {
$data = $this->_request->getPost();
//Code should come here
array(
item1(
array(
value1 = item[0][0] //From javascript array
value2 = item[0][1]
)
)
item2(
array(
value1 = item[1][0]
value2 = item[1][0]
)
)
)
}
I'm a n00b in Zend and any help would be much appriciated :)
Instead of the below code:
$data = $this->_request->getPost();
Use the following code:
$data = $this->_request->getParams();
print_r($data);
This will give you the array as you are sending from javascript.
In your javascript file declare your array:
var item = [[1,2],[3,4]];
Then in your ajax call you should modify the data sent to be JSON. Replace the line
data: item
with
data: {data: JSON.stringify(item)}
Then, in your controller you can decode the data send to get your array:
$data = json_decode($this->getRequest()->getPost("data"));
and you have your array.

Transfer JavaScript Array to PHP array using ajax?

I am trying to transfer a list of data from a javascript array to a php array and I can't seem to get ajax to do the trick. Can someone show me the code on how to do this? So far here is what I have, which is just the array:
JAVASCRIPT
var dates;
// the dates array is then filled up here
// it contains information in the form {'2012-01-01', '2012-03-12', ...}
$.ajax({
type: "REQUEST",
url: "NAMEOFPHPFILE.php",
data: { sendData1 : dates },
success: function() {
alert("Attempting to transfer array -> AJAX");
}
});
var submissions;
// the submissions array is then filled up here
// it contains information in the form {int, int, ...}
// ect ......... with 3 more arrays using { sendData2 : submissions },
PHP
<?php
$bDates = $_REQUEST['sendData1'];
// need to set this array = to the JavaScript dates array
$bSubmissions = $_REQUEST['sendData2'];
// need to set this array = to the JavaScript submissions array
?>
I would prefer to use the REQUEST method to prevent information logging into the URL. This code also doesn't work when trying POST instead of REQUEST
At the very end of the .php page, I am outputting a bunch of arrays onto a CSV page where I iterate through the arrays and place their elements in the file. This already works, but I need to transfer some of these arrays from javascript to PHP so that I can spit out the data. That looks like this:
<?php
$stringData = "Dates, Number of Lines Changed, , Bug Dates, Arrivals, Fixed, Closed, Hold_";
for($i = 0; $i < sizeof($dataXAxis); $i++){
$date = substr($_REQUEST['Dates'][$i+1], 0, 24);
$stringData .= "$date, $dataYAxis[$i], , $bDates[$i], $bSubmissions[$i], $bCompletions[$i], $bDones[$i], $bRejections[$i]_";
}
echo '<BR><BR>Download Your CSV File';
?>
Why doesn't the AJAX work? The arrays appear empty...
One method would be to try sending the data in the form of JSON. Then using json_decode, you can convert it to an array. Example:
var Json = {"User1":"John", "User2":"Joe", "User3","Jerry"};
var data = "data="+Json;
hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
console.log(hr.responseText);
}
}
hr.open("POST", "parsefile.php", true);
hr.send(data);
Then when you get the data in your PHP file it's something like:
$data = $_POST['data'];
$array = json_decode($data, true);
This all will tell php to turn our data into an assosciative array. It can then be manipulated as an assosciative array.
I was literally just working on this.
jQuery
var group_ids = $('.form-elements li').map(function(){
return $(this).data('group-id')
}).get()
$.get('{{ url('group/update_order_by') }}', {group_ids: group_ids});
PHP from the restful Laravel framework
public function get_update_order_by()
{
$group_ids = Input::get("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
$group = Group::find($group_ids[$i] );
$group->order_by = $i;
$group->save();
}
return true;
}
Raw PHP (ugh...)
$group_ids = $_GET("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
echo $group_ids[$i];
}
return true;
The simply convert an array to string
var data = [1,2,"hello"];
var data_str = data.join(",");
and afterwards convert the string to array in php:
$array = explode(",", $_REQUEST["data"]);
In PHP, the REQUEST expects arrays to be passed in the following format:
sendData1[]=first&sendData1[]=second&sendData1[]=third
This is automatically converted into an array:
$sendData = $_REQUEST['sendData`];
echo $sendData[0];
echo $sendData[1];
First, for the sake of simplicity, create an array holding both arrays you want to send and parse:
var request = Array(dates, submissions);
Second, make sure you're sending your request as properly formatted JSON. In addition, when testing I recommend returning the output from the remote file in your callback to see how your data was parsed. I recommend the following implementation, as well as sending via POST:
$.ajax({
type: "POST",
url: "NAMEOFPHPFILE.php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(request),
success: function(data) {
alert(data);
}
});
In your PHP file, get you can parse the contents of the aforementioned request into an array using the following:
<?php
// convert json data read from the input stream to an array
// *note* you MUST set the true flag in the json_decode() function, otherwise it will convert the data into an object
$request = json_decode(file_get_contents('php://input'), true);
var_dump($request);
You should now get an alert containing the var_dump of the array(looks messy, I know!).
This should be enough to get you started, hope it helps!

Categories