Create new multidimensional Associative array from 2 arrays

前端 未结 3 1600
陌清茗
陌清茗 2021-01-15 12:15

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

相关标签:
3条回答
  • 2021-01-15 12:55

    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];
    
    0 讨论(0)
  • 2021-01-15 12:58

    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 ]  
    }
    
    0 讨论(0)
  • 2021-01-15 12:59

    This :

    changes[key[newValue]]
    

    Should be:

    changes[key][newValue]
    
    0 讨论(0)
提交回复
热议问题