Jump to content

Recommended Posts

In php...

<?php

function myfunction($id, $name)
{
    $ids = array();
    $names = array();
    foreach ( $id as $name )
    {
        array_push($ids, $id);
        array_push($names, $name);
    }
}

?>

 

What I'm trying to do is take a variable that is pushed by a generator and add it to an array each time the page is loaded.  In PHP, my function would look something like the above php code.  How do I add, one at a time, two different variables being pushed from the generator into two different arrays using one function?

Link to comment
https://forums.phpfreaks.com/topic/171993-solved-adding-to-arrays/
Share on other sites

Better yet...

I know that you can do multi-dimensional arrays in JS, so if I had an array like...

 

// Array Model
var myArray = [
    ["NameOfID", "_id"]
];

// Two variables being passed to my function hopefully...
// varName and varID will be variable holders
// Would my function look something akin to this?
function getInfo(varName, varID)
{
    var myArray[];
    var i = 0;
    for (i=0; i != null, i++)
    {
        myArray.push([varName],[varID]);
    }
}

 

Now, how do I push data into that array based on what's passed to the function (as a string).

 

Note: there will be multiple (quantity varies) names and ID's passed, each going as a matched pair (of name and ID). 

I guess I should ask, is passing data to a JS function possible in the manner that I'm trying to do?

:)

 

Edit: Attempted to write a function... :)

It would actually be awesome if I could push both pieces of data into one array, that way I can pull both parts from the same array.

 

I feel like I'm making this overly complicated.  I need to add two individual strings into an array to be manipulated later in a different frame.  Unfortunately my environment does not support PHP, otherwise this would be a snap...

Arrays are arrays are arrays.  They behave pretty much the same across languages.  All that's different is the syntax.  What you're looking for isn't a multidimensional array, but an associative array/hash.  Something like:

 

var ids = new Array();

function setId(key, value){
   ids[key] = value;
}

function getId(key){
   if (ids[key]){
      return ids[key];
   }
   else{
      alert("There is no ID available for " + key);
   }
}

var name = "Test";
var id = 1;

setId(name, id);
var result = getId(name);

Nightslyr, thats an awesome response, but how do I add to the array for each chunk?

 

Eg: There will be a variable, called ID and NAME and each one will be spitting out an array.

 

Eg: Array{ [_KEN, Enter], [_K03, Exit], [_KHL, Help] ... } <-- what the array should look like after the page loads...

 

The function you give works yes, but how do I add to the array, populating it like so?  Also, all of the ID's are in the form of: _K##

 

Ultimately, I will be creating a function that takes this populated array and writes buttons (Name = Text on Button, ID = button.name and button.id) in a different frame.

Names...
Array
(
    [0] => Enter
    [1] => Exit
    [2] => Help
)

ID's...
Array
(
    [0] => _KEN
    [1] => _K03
    [2] => _KHL
)

 

This should demonstrate exactly what I'm trying to do...  These arrays only have 3 values in them, but ultimately there will be an unknown number of matched pairs.  For example, the text that goes with _KEN is 'Enter'.  Now, if the arrays look like this, how do I write a function in JS to take the output (one at a time) of echoed ID's and Names?

 

And yes, adding to arrays and objects is simple (when you're doing it manually, one item at a time).  But adding to arrays and objects dynamically is more difficult, and the reason I'm here :)

And to finish off my PHP function for taking data and rearranging it...

 

<?php

function myfunction($id, $name)
{
    $ids = array();
    $names = array();
    foreach ( $id as $name )
    {
        array_push($ids, $id);
        array_push($names, $name);
    }

$data = '';
foreach ($ids as $value) 
{
	$data .= "<input type='submit' name='".$ids['$value']."' id='".$ids['$value']."' value='".$names['$value']."'>";
	return $data;
}
}

?>

 

This php function shows that I'm trying to do in JS... I need to do this in JS.

Again, if you are certain that the keys will only match one value, then simply use an associative array like I showed you above.  Example, since it seems like you're having a hard time understanding me...

 

Your array should look like:

 

Your array...
(
    ["_KEN"] => "Enter"
    ["_K03"] => "Exit"
    ["_KHL"] => "Help"
)

 

The ids are the keys, and the values are mapped to each one.  You can add to the array, or retrieve individual values with the functions I showed above.  Also, JavaScript has a for...in construct which works similarly to PHP's foreach:

 

for (var i in myArray){
   alert("Key value is: " + i + "  Value is: " + myArray[i]);
}

 

Like I said originally, arrays are arrays are arrays.  They behave in nearly identical ways regardless of what language you use to create and access them.  What you can do in PHP you can do in JavaScript with only a few minor syntactical changes.

 

Dont use JavaScript arrays if you're going to have a key that isnt an integer. Use an object.

 

var obj_arry = {}; //or new Object();

 

//add to object is simple

obj_arry[key] = value;

 

This is pretty pointless as an array is also an object in JavaScript, and would be used in exactly the same way.

Nightslyr - http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

 

Also, for in loop will loop over the Array Object's methods as well, avoid it for arrays

 

geudrik - your php function makes no sense to me. When you call the function, the ids array is set to an empty array. are the arguments id and name arrays?

 

You can easily add to a javascript array using the push() method

 

arr.push(value)

 

What you want to do would work better with an object literal, like I said above.

 

var obj = {};

obj[id] = name;

 

//use for in on the obj

for(id in obj){

//id is your id

//obj[id] is your name

}

 

 

Interesting.  The following statement is wrong, however:

 

Also, for in loop will loop over the Array Object's methods as well, avoid it for arrays

 

As the code below works without alerting out array methods:

 

<html>
<head>
   <title>Blah</title>
   <script type="text/javascript">
      window.onload = function(){
         var oArray = new Array();

         oArray["_KEN"] = "Enter";
         oArray["_K03"] = "Exit";
         oArray["_KHL"] = "Help";

         for (var key in oArray){
            alert("Key value is: " + key + " Value is: " + oArray[key]);
         }
      }
   </script>
</head>

<body></body>

</html>

 

You/the article are right about the length property returning 0 if the keys are strings.  Unfortunately, it appears as though the length property doesn't work for objects at all, as I get 'undefined' when trying to alert it out.  :shrug:

 

I guess the safest conclusion is that for a real associative array, one should create a custom object that has a method to return its length.

Interesting.  The following statement is wrong, however:

 

Also, for in loop will loop over the Array Object's methods as well, avoid it for arrays

 

As the code below works without alerting out array methods:

 

<html>
<head>
   <title>Blah</title>
   <script type="text/javascript">
      window.onload = function(){
         var oArray = new Array();

         oArray["_KEN"] = "Enter";
         oArray["_K03"] = "Exit";
         oArray["_KHL"] = "Help";

         for (var key in oArray){
            alert("Key value is: " + key + " Value is: " + oArray[key]);
         }
      }
   </script>
</head>

<body></body>

</html>

 

Did you try this code in ALL browsers?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.