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?
More complete example: (also note I put category instead of categorie, change if needed).
Key things to take away from this approach:
.pushcan be used on a javascript array to add an item to an arrayUsing a string as a type for an object:
EDIT
I gave it some more, thought and after reading this, it turns out that
arraysin 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 anobjectinstead is better. For example, the following:Also, if using a debugger, such as Firebug in Firefox, you can see detailed info with the
console.dirfunction.