Creating a Javascript version of a PHP multidimensional associated array - php

I have a set of data that is not normalized. I do the normalization in PHP it it works just fine.
The dataset looks like this (screenshot bellow), it is a lot larger tho. I am only interested in orginizing the category and the type. With those two orginized I can make good tables and menu's.
Problem
Now the problem is, I am switching to an AJAX system, and the data no longer comes into PHP. Instead it comes directly into the page using node.js/mongodb. Is there a way I can do something like this:
<script type="text/javascript">
// Array containing all the objects from the server
// looks like this
var data = [Object, Object, Object];
var artikelen = [];
for(var i=0; i<data.length; i++){
artikelen[data[i].categorie][data[i].type][] = data[i];
}
</script>
// ----------------
OLD SITUATION
//-----------------
In PHP I did this:
$sql = "SELECT *
FROM mydb
WHERE merk = 'webecos'
ORDER BY categorie, type, code";
$result = $wpdb->get_results( $sql );
foreach($result as $row){
$artikelen[$row->categorie][$row->type][] = $row;
}
Now I can make good sorted tables / menu with nested loops. The code I used is this.
<ul id="inkoop_menu">
<?php foreach ( $artikelen as $categorie => $row ): ?>
<li>
<a class="inkoop_button" data-menu="categorie" href="#">
<?=$categorie; ?>
</a>
<ul>
<?php foreach ( $row as $type => $artikel ): ?>
<li>
<a class="inkoop_button" data-menu="type" href="#">
<?=$type; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul>
Edit
Maybe this is a but better to understand. The array I am after looks like this:
array['categorie-name']['type-name'][x] = whole object;

I'm not really sure I totally follow you, but do you mean something like this?
var data = [Object, Object, Object];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
More complete example: (also note I put category instead of categorie, change if needed).
<script language="javascript" type="text/javascript">
var obj1 = new Object();
obj1.category = 1;
obj1.type = 2;
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
alert( artikelen[1][2] ); // expected [object], [object]
alert( artikelen[1][2][0].type ); // expected 2
</script>
Key things to take away from this approach:
Check if array at key exists
If not, create it
.push can be used on a javascript array to add an item to an array
Using a string as a type for an object:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
alert( artikelen[1][2] ); // expected [object], [object]
alert( artikelen[1]["hello hello"][0].type ); // expected "hello hello"
EDIT
I gave it some more, thought and after reading this, it turns out that arrays in Javascript are not well suited to be used as associative arrays (like in PHP). In actuality, you are just adding attributes to an object. So making it an object instead is better. For example, the following:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Object();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Object();
artikelen[data[i].category][data[i].type] = (data[i]);
}
console.dir( artikelen ); // if using a debugger with console, gives detailed info
Also, if using a debugger, such as Firebug in Firefox, you can see detailed info with the console.dir function.

Are you still able to work with PHP? If so, you can always bring the data from the server in the JSON format and let the client (in your case, the javascript language) read it and interpret it.

Related

Object in jquery using json response

I want to create an object in jquery using a json response that is return from my controller
var cellContents = {'29-08-2018': '20','18-08-2018': '60'};
This is the desired format that i want and below given is my json response
{"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]}
i tried some code to make the format that i want but it failed this is the code that i tried
var arr2 = [];
//var cellContents = JSON.parse(data.result);
for(var i=0; i<data.result.length; i++){
var arr = [];
for(var j=0; j<data.result[i].date.length; j++)
{
arr.push(parseInt(data.result[i].date[j].fcount));
}
var test = [data.result[i].followup_datee];
arr2.push(test.concat(arr));
}
var jsonString = JSON.stringify(arr2);
console.log(jsonString);
after i tried this code i got some response in the console like this
[["17-08-2018",1],["18-08-2018",1]]
This is the controller that i am using in php
public function getLeadcount()
{
$status = 1;
$arr = [];
$sess = $this->session->userdata('user_id');
$result = $this->mdl_lead_registration->getLeaddate($sess);
if(!empty($result))
{
$status = 1;
foreach($result as $res)
{
$res->{'date'} = '';
$res->date = $this->mdl_lead_registration->getLeadcount($sess,$res->followup_datee);
}
}
echo json_encode(array("status" => $status,"result" => $result));
}
I think you all understand my problem . Any sort of help is appreciable.
Use the following code:
var data = {"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]};
var obj = {};
for (var i = 0; i < data.result.length; i++){
obj[data.result[i].followup_datee] = parseInt(data.result[i].date[0].fcount);
// Here you change the property.
// In js you can access to an object's property like an array,
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors.
// If you want to use the count as a string, use instead:
// obj[data.result[i].followup_datee] = data.result[i].date[0].fcount;
}
console.log(obj);

Get variables fom a txtor php file

I have this code on .fla file
fm_button.visible = false;
var menu_label:Array = new Array("Introduction", "Products", "Services",
"Testimonials", "Our Company", "Contact Us");
var total:Number = menu_label.length;
var i:Number = 0;
var page:Number;
var main_menu:MovieClip = new MovieClip();
stage.addChild(main_menu);
for (i = 0; i < total; i++)
{
var btn = new flashmo_button();
btn.name = "btn" + i;
btn.x = fm_button.x;
btn.y = fm_button.y + i * ( fm_button.height + 10 );
btn.buttonMode = true;
btn.item_no = i;
btn.flashmo_click_area.addEventListener( Event.ENTER_FRAME, btn_enter );
var each_substring:Array = menu_label[i].split("|");
btn.flashmo_button_label.fm_label.text = each_substring[0];
btn.item_url = each_substring[1];
main_menu.addChild(btn);
}
function btn_over(e:MouseEvent):void
{
e.target.parent.over = true;
}
function btn_out(e:MouseEvent):void
{
e.target.parent.over = false;
}
What i want is to get this values:
("Introduction", "Products", "Services", "Testimonials", "Our
Company", "Contact Us");
from a text or php file named menu.php or menu.txt
Is this possible?
Why you need read from .php file?
Is this client-server communication?
In that case, when .fla file loads by client browser over http(s) you should do something like this:
menu.php (for example put this file to document root folder):
<?php $menu = array('Elem1', 'Elem2');
echo json_encode($menu); ?>
.fla:
var sendData:URLVariables = new URLVariables();
var request:URLRequest = new URLRequest('/menu.php');
request.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader(request);
loader.addEventListener(Event.COMPLETE, onCompleted);
So, your .fla are doing query to server and get's list of categories (onCompleted method receive data).
If this is not server-client communication, you should use other file format, because .php is not a data storage )

How we can get that at a particular place marker is present or not

I am making dynamic markers. I got success in that. But here is problem that if there is two same lat-log then it place only one marker there.
Instead of that I want to change the marker icon if there is two same lat-log.
I am taking lat-log from database.
Any help.
Yes, I have found the solution of this problem.
I am using two array
The code is as following:
var contentStrings = new Array();
var markers = new Array();
and getting the position
var pos = marker.getPosition();
var isPresent = false;
var index;
for(var i = 0; i < markers.length; i++) {
if(String(pos) == String(markers[i])) {
isPresent = true;
index = i;
}
}
if(isPresent) {
contentString = contentStrings[index] + '<div><br/> Tutor Name : '+data.name+'<br/>Link : '+data.url+'</div>';
} else {
markers.push(pos);
contentString = '<div> Tutor Name : '+data.name+'<br/>Link : '+data.url+'</div>';
contentStrings.push(contentString);
}
Its really working fine.

Pass a PhP string to Mootools in Wordpress

I have a foreach loop that creates a string in php , I'm unable to pass the string value to mootools in wordpress (I'm integrating a MooTool function ) :::
I need to substitute the "hard coded" image URL's in the new Array() (below) with a variable created from my php string eg. new Array( $myimageurl ) :::
I've created a var from the php string even tried json_encode , with no luck :::
window.addEvent("domready", function(){
var counter = 0;
var images = new Array('http://localhost/square/wp-content/uploads/2011/10/test-foo/foo.jpg','http://localhost/square/wp-content/uploads/2011/10/test-foo/foo1.jpg');
er, why not just:
var foo= <?=json_encode(Array("foo.jpg", "bar.jpg"))?>;
EDIT
Since you implied in a comment your files source is comma separated, then do this instead:
<? $files = "foo.jpg,bar.jpg"; ?>
var foo = <?=json_encode(explode(',', $files))?>;
where the array could be anything of any length, read from wherever. it will result in an array literal looking like so:
var foo = ["foo.jpg","bar.jpg"];
// eg use.
foo.each(function(img) {
new Element("img", {src: img}).inject(document.body);
));
nb: just noticed #Marc B has already mentioned json_encode. sorry, will delete
try:
var images = new Array('<?php echo $miImageUrl[0];?>', '<?php echo $miImageUrl[1];?>');
Other way:
<?php
//sample data
$descargables[0] = 'cero';
$descargables[1] = 'uno';
$descargables[2] = 'dos';
$descargables[3] = 'tres';
// end sample data
$arrayToJs="var descargables = new Array();";
for ($i=0; $i < count($descargables); $i++) {
$arrayToJs .= "descargables[" . $i . "]='" . $descargables[$i]. "';";
}
?>
<script>
<?php echo $arrayToJs;?>
idx = 3;
alert("descargable:" + descargables[idx]);
</script>

php to js array convert with jquery's ajax

Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander
Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}
For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.
You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>

Categories