Create new multidimensional Associative array from 2 arrays

拥有回忆 提交于 2019-12-01 11:19:47

It's really unclear what you want, but there are a couple of serious flaws with your logic:

  1. 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.

  2. 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.

  3. 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.

  4. 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]

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!