I am looking for a solution to create a single multidimensional associate array in javascript.
What I have: I have a mysql database I am accessing with php and have
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
Use aliases for the numeric indices to do this:
var foo = ["Joe","Blow"];
var bar = ["joe","blow"];
var names = {};
foo.fname = foo[0];
bar.fname = bar[0];
foo.lname = foo[1];
bar.lname = bar[1];
names.fname = [foo.fname,bar.fname];
names.lname = [foo.lname,bar.lname];
It's really unclear what you want, but there are a couple of serious flaws with your logic:
var changes={}; ///this one way of declaring array in javascript
No, it isn't. That's an Object, which is very different from an array.
eval(<? echo json_encode($oldInfo); ?>);
You don't need eval
here. The output of json_encode
is JSON, which is a subset of JavaScript that can simply be executed.
changes[key[value]]=value;
This is totally wrong, and still a single-dimensional array. Assuming key
is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...
'a' => 1
'b' => 2
'c' => 3
... then changes
will look like this after:
1 => 'a'
2 => 'b'
3 => 'c'
For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value
.
Your variable naming is wrong. You should never see a line that reads like this: key[value]
. That's backwards. The key goes between the []
, the value goes on the other side of the =
. It should read something like array[key] = value
.
RE: Your clarification:
This doesn't work: {fName=>{"charles","Charlie"},...}
. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"]
for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"}
syntax.
You want an array, where each key is the name of a property and each value is an array containing the old and new values.
I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.
var changes = {};
var oldInfo = <?= json_encode($oldInfo) ?>;
function change(key, value) {
changes[key] = [ oldInfo[key], value ]
}
This :
changes[key[newValue]]
Should be:
changes[key][newValue]