Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Storing Variables - Multi Dimensional Array

    Hi Everyone,

    I'm somewhat new to PHP and can't seem to display what I want. I'm attempting to store data in a multi dimensional array and pull it out when need be. I came up with the code below but it doesn't seem to work properly.

    Code:
    $file = file("list.txt");
    foreach ($file as $line) {
    
    $table = array(
            array('name' => $line, 'val' => $val, 'perc' => $perc));
    
    }
    
    foreach($table as $name => $entries){
            foreach($entries as $key => $value) {
                    echo "$name t $key t $value";
            }
    }
    Here's the output:
    Code:
    0 t name t LIZ
    0 t val t 0.7020 t perc t -0.038 (-5.14%)
    How do I go about getting the second set of data to not overide the first. I attempted :

    Code:
    $file = file("list.txt");
    foreach ($file as $line) {
    
    $table[] = array(
            array('name' => $line, 'val' => $val, 'perc' => $perc));
    
    }
    
    foreach($table as $name => $entries){
            foreach($entries as $key => $value) {
                    echo "$name t $key t $value";
            }
    }
    or

    Code:
    $file = file("list.txt");
    $i=0;
    foreach ($file as $line) {
    
    $table[$i] = array(
            array('name' => $line, 'val' => $val, 'perc' => $perc));
    $i++
    }
    
    foreach($table as $name => $entries){
            foreach($entries as $key => $value) {
                    echo "$name t $key t $value";
            }
    }
    Any help would be greatly appreciated..

    BigJoeJack

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    This is very close, you just need to define the first level array outside of the foreach:
    PHP Code:
    $file file("list.txt");
    $table = array();
    foreach (
    $file AS $line)
    {
        
    $line trim($line);
        
    $table[] = array('name' => $line'val' => $val'perc' => $perc); // I don't know where the $val or $perc come from though...
    }

    foreach(
    $table as $name => $entries){
            foreach(
    $entries as $key => $value) {
                    echo 
    "$name t $key t $value";
            }

    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #3
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you very much. That worked perfectly! $perc and $val are dynamic and come from a regex function on text during the foreach loop.

    However, the output has the index showing as well.

    0 G0 0.7330 -0.033 (-5.44%)1 L1 0.7331 -0.033 (-5.44%)
    |--|----|-------|-----------|--|-----|------|
    index --val-----perc--------index----val-----perc

    Is there a way where i can just specify the variable? For example, instead of $value, i could specify just val, name or perc?

    Code:
    $table[] = array('name' => $line, 'val' => $val, 'perc' => $perc); 
    
    foreach($stock_table as $name => $entries){
            foreach($entries as $key => $value) {
                    echo "$name $value";
    }
    }
    instead of using key value, can i specify name, val or perc?

    Thanks again, for all your help!

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    I don't quite understand what you're describing, but if I follow you correctly you just want to control what is what.
    In a multi-dimensional array like you have here, this line: foreach($stock_table as $name => $entries) would create an array represented of $entries. This array would contain the offsets 'name', 'va' and 'perc'. You can access each of these using their key offset (PHP doesn't actually have an array datatype, it only uses hashmaps):
    PHP Code:
    foreach ($stock_table AS $entries// You probably can abandon the key here:
    {
        
    printf("%s\t%s\t%s\n"$entries['name'], $entries['val'], $entries['perc']);

    By controlling what $entries offset you're using determines what you'll get for output.
    If I'm mistaken, perhaps you can indicate what kind of output you're expecting and we can go from there.

    Edit:
    Ok, I think I got what you're after. The answer is no you can't, in a foreach you can only specify the key/value pair. Using a single level foreach combined with a list you can get what you want:
    PHP Code:
    foreach ($stock_table AS $entries)
    {
        list(
    $name$val$perc) = $entries;

    Now inside of you're foreach you can handle $name, $val and $perc individually. Methinks that is more in line with you're actual question.
    Edit:
    Lol, overlooked something. List can only be used with numerical arrays, not with string keys so you cannot actually use it for you're current code. If you dump the array index handling than you can use it (I'd stick with the indexes, its less memory and therefore faster that way).

    Last edited by Fou-Lu; 10-12-2009 at 04:59 AM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #5
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks again for helping me out. I think at this point, I should explain to you exactly what I'm trying to accomplish so were both on the same page.

    The program I created opens a file, reads each entry then put certain values within the file into an array for calculation that will happen. I have a feeling I'm going the wrong way so your feedback will be extermely insightful.

    In the file, I pull three types of information per line using regex and place them into a variable.

    Code:
    $val = preg_match(....code....);
    $val = $matches[0];
    
    $perc = preg_match(....code....);
    $perc = $matches[0];
    Each line provides me a unique name and two values as strings. From there, I store these values in a multi-dimensional array which I use to display later but also to do calculations [not setup yet].

    Code:
    foreach ($file AS $line)
    {
        $line = trim($line);
    
    $val = preg_match(....code....);
    $val = $matches[0];
    
    $perc = preg_match(....code....);
    $perc = $matches[0];
    
    $table[] = array('name' => $line, 'val' => $val, 'perc' => $perc);
    }
    Where it get's complicated is that the file changes and the script is setup to loop and reopen the file then follow the same process over again. This time, the script will gather the same info but store it in table array.

    When it loops, the old data cannot be deleted so I assume my array needs to becomes the following:
    Code:
    $table[][] = ...
    I will then pull out the data and calculate total/average for the two values of each name which was pulled line by line.

    Does this give you a better understanding? I bought me a couple of books and dove right in however was a little overwhelmed due to inexperience with arrays.

    Thanks again,

    BigJoeJack
    Last edited by bigjoejack; 10-12-2009 at 05:59 AM.

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Seems like a lot of work. Rule of thumb (my thumb ) is to limit resource usage (ie: file handling, database handling, etc) to the bare minimum you can. This means you should only open and handle you're file once, though you can feel free to go over the file multiple times (this cannot be done with the file() function, but instead using an fopen and fseek/fread combinations).
    Another option is serialization. This lets you serialize an array into a string representation, store this in a file, and read it back in, unserialize and you've got you're array back. Objects are the final approach, and are also serializable (using either __sleep/__wakeup magic methods or by implementing Serializable interface). Objects are advanced PHP handling.

    It makes the most sense from what you have here to use a multi-dimensional array. This will let you 'see' each of the entries as their own array in a collection of another array.
    Can you post a few entries from you're text file and what the represent? Chances are using an sscanf or fscanf will let you read you're file and parse it faster/easier than using a preg_match.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #7
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks again for the quick response. I really appreciate the help.

    Ok, I made a mistake earlier stating that the $val and $perc came from the file, it actually comes from a page on our intranet webserver.

    This program reads from a file, which in turns provides a line ($line). This line is a product in inventory on our intranet that I want to monitor. I want to track two values (percentage/value) for each item. The information on the webserver is provided by a legacy application that outputs cryptic data (junk\garbled) to a internal webserver for manufacturing department. There is one guy who daily reads this data but if he's sick and upper mgmt needs some info, I get in trouble and stuck manually reading html files and searching for info.

    Hence why I'm writting this app so I don't lose half a day manually searching!

    So here's the break down one more time with more details:
    Code:
    $file = file("list.txt");
    $table = array();
    foreach ($file AS $line)
    {
        $line = trim($line);
    list.txt contains the following lines.. (more will be added when working)
    LIZ
    METAL

    The script then goes to the internal webserver and saves the page to a variable.

    Code:
    $s = curl_init();
    
    # Configure the cURL command
    curl_setopt($s, CURLOPT_URL, "http://127.0.0.1/$line"); // Define target site
    curl_setopt($s, CURLOPT_RETURNTRANSFER, TRUE);          // Return in string
    curl_setopt($s, CURLOPT_FOLLOWLOCATION, TRUE); // Follow header redirections
    curl_setopt($s, CURLOPT_MAXREDIRS, 4);         // Limit redirections to 4
    curl_setopt($s, CURLOPT_TIMEOUT, 30);   // Don't wait longer than 30 seconds
    
    # Execute the cURL command (send contents of target web page to string)
    $web_page = curl_exec($s);
    I need permission to post the page content so for now, I'll just make something up. It's mostly HTML/JavaScript with 2 informations that are important barried inside ($perc, $val ).

    After a couple of days trying to get the above working with regex, I impressed myself by getting it somewhat operational!

    The next step uses regex to gather the 2 values ($perc, $val) and put it in an array with $line.

    Code:
    $val = preg_match(....code....);
    $val = $matches[0];
    
    $perc = preg_match(....code....);
    $perc = $matches[0];
    
    $table[] = array('name' => $line, 'val' => $val, 'perc' => $perc);
    }
    I can't remember what the refresh rate is for the information on the webserver but my program will most likely sleep for 1hr before restarting the entire process adding more info to the table.

    I will then pull out the $val, $perc for each iteration for every $line and calculate the average and total.

    For example,

    <-- first iteration -->
    LIZ
    1
    50

    Metal
    -1.334
    11.720

    <-- Second iteration -->

    LIZ
    4
    22

    Metal
    2
    0.440

    Calculation
    $total_a = $value[iteration] + value[iteration2] + value [....]
    $total_b = $value[iteration] + value[iteration2] + value [....]

    I know I've thought of a difficult project but it will save me loads of time in the future and well worth the effort. I've also taken two c++ classes in college back in 2004.

    Although, I never thought I'd use it! :-)

    BigJoeJack

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Ok gotcha. Yeah, this is tricky since you have more than one resources.
    The only suggestion I can make to simplify processing would be to create another file or use another resource like a DB. I assume that when you're contacting the service that it only gives you up to date information, while you need to track previous data as well?
    Each script load will destroy any information previously associated. For that, yes you'll need to append with [][] instead of just []. The other option is to merge the data or replace, sounds to me like you can replace but you'll need to load the previous data, extract the new data, compare and replace and than rewrite.
    Man, for such little code (~45-60 lines I'm guessing here?) this is a rather hefty task.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #9
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks again. You've discouraged me somewhat but I'm still optimistic to get this running.

    I guess I could always use mysql to store the data and I do have a little experience using it. I'm volunteering today at a homeless shelter but when I get back, I'll start reading up on mysql again.

    I'll update you on the new code when I have a chance. Thanks for all your help and advice, I really appreciate it!

    Sincerely,

    BigJoeJack

  • #10
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Don't be discouraged; I was only trying to point out that some of our 'dirty' tricks may not help in this situation since you have a few resources in use. Besides, this is like the perfect resource project ever, so you will learn a lot by doing this.
    The really tricky part (since it sounds like you have a lot of this working as is), is to simply track you're 'old' data so you can use it later in you're calculations.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •