51 users online (0 members and 51 guests)  


Page 1 of 2 1 2 Last
  Results 1 to 15 of 18

Related

  1. Syntax for Select Statement    Forum: Databases
    Replies: 2
  2. If statement inside <td>    Forum: CGI Perl Forum
    Replies: 1
  3. Replies: 4
  4. Sql statement    Forum: PHP Forum
    Replies: 1
  5. Select Case SQL Statement...    Forum: Databases
    Replies: 7
  1. #1
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Use a foreach statement to build an array

    What I have is a foreach statement, going through the elements of an array.

    For each element I would like to add a value to a different array depending on certain conditions. Example:

    PHP Code:
    foreach ($array as $value) {
      if (
    condition){
        
    //add a certain value to a completely different array, call it "$differentarray"
      
    } else if (another condition) {
        
    //add a certain value to $differentarray
      
    etc etc etc 
    I can't figure out how to incrementally add these values one each run of the foreach and then end up with a complete array..

    If this explanation isn't clear, just ask for more clarification please.

    Thanks,
    Tom
    Last edited by deliriousthunder; 06-02-2009 at 04:40 AM. Reason: PHP code tags

  2. #2
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    Re: Use a foreach statement to build an array

    To add a value to an array, the simplest way to do it is to use code similar to the following (modifying your code):

    PHP Code:
    $differentarray = array();
    $differentarray2 = array();

    foreach (
    $array as $value) {
      if (
    condition){ 
        
    //add a certain value to a completely different array, call it "$differentarray" 
        
    $differentarray[] = $value;
      } else if (
    another condition) { 
        
    //add a certain value to $differentarray
        
    $differentarray2[] = $value;
      } 

  3. #3
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    Thanks. I figured I could do it that way, but I wasn't sure how it would work. Let me explain a little more.

    PHP Code:
    $differentarray = array();
    // No, I just want to end up with one array when the foreach
    // statement finishes executing *NO*$differentarray2 = array();*NO*

    foreach ($array as $value) {
      if (
    condition){ 
        
    // Ok, this is what I would like to do:
        
    $differentarray[] = $array->id// but I'd also like to add
        // another value to the array
        
    $array->name;
      } else if (
    another condition) { 
        
    // Then I pretty much want to do the same thing:
        
    $differentarray[] = $array->id// AND
        
    $array->name;
      } 
    So if I was to var_dump($differentarray), it would look something like:

    array() { [0]=>sometext { ["id"]=> string(1) "3" ["name"]=> string (10) "abcdefghij" } [1]=>somtext { ... etc etc etc
    Basically, the purpose of this is to filter the original array based on certain conditions, and create a new one from the results.

    The original array has a lot more to it than just these 2 fields, but I only need those 2 fields in the new array.

    So the idea is:
    foreach of the objects in the array
    if any one of a number of conditions is true
    add 2 of the "fields" from that array object to a different array
    otherwise ignore the object and move on to the next object.
    The result being an array with a number of objects, containing only 2 of the original fields for those objects.

    I'm not sure how to go about adding those 2 values to the array though.

    For your info, I do not usually write my own code, most of my work consists of modifying other peoples code. As a result, I haven't really learned much of the language in depth, reading and modifying code that is already written doesn't usually require an exhaustive knowledge of the language, just the ability to work out what the code is doing, and follow the original syntax to modify it.

  4. #4
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    Ok, with a bit of googling, experimentation/problem solving, and taking on board jthaynes advice, I got it do what I wanted.

    Now that I have a working implementation I have realised that it just will not be viable when the site goes live, the page loading time would go through the roof.

    Now I'm going to have to try to figure out a way to get the info I need directly from a MySQL query, (or even multiple queries) which should be quicker.

    Currently it queries 2 tables, joining them on a field, and creates one big array. I am then filtering that array down to only take certain objects from it, depending on certain conditions. I knew this would be slow, but it's very difficult to get the info I need directly from the database, so I had just hoped it wouldn't be this bad.

    Ah the joys..
    Last edited by deliriousthunder; 06-02-2009 at 06:21 AM. Reason: Grammar

  5. #5
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    Re: Use a foreach statement to build an array

    If you would like, I can help you come up with an easier way to do it. Feel free to PM me with any questions/details.

  6. #6
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    Thanks

    I'll PM you if I need to keep any of the details private, but at the moment this can be public. Maybe then someone else will benefit from this thread.

    I'm in the process of writing a query to get the info I need.

    I've never actually tried this before, so maybe you can tell me if it is possible. Example:

    $query = ' SELECT g.field_1 AS value, g.field_2 AS text, g.field_3, g.field_4, m.field_5, m.field_6, m.field_7, m.field_8
    FROM #__table AS g
    LEFT JOIN #__related_table AS m ON m.field_5 = g.field_1
    WHERE m.field_6 = '.$variable.' AND g.field_3 = \'2\'
    OR
    WHERE m.field_6 = '.$variable.' AND m.field_8 = \'1\' AND g.field_3 = \'1\'
    OR
    WHERE g.field_4 = '.$variable.' AND g.field_3 = \'0\' '
    This query, (if there is even an "OR" operator, I don't know), won't return any duplicate entries in the array. However, it will return some entries that have duplicates of the 2 fields fields I need to be displayed to the end user.

    So I will also need to figure out a way to stop duplicate entries from being displayed, it won't matter if they are actually there or not, as long as the end user doesn't see them.

    First things first though, will the query work?

    Thanks,
    Tom

  7. #7
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    Re: Use a foreach statement to build an array

    First, there is an OR operator. Your query needs to be changed slightly as the WHERE keyword must be unique within the query. In other words, set it as follows:

    Code:
    $query = 'SELECT g.field_1 AS value, g.field_2 AS text, g.field_3, g.field_4, m.field_5, m.field_6, m.field_7, m.field_8 FROM g_table AS g
    LEFT JOIN m_related_table AS m ON m.field_5 = g.field_1
    WHERE (m.field_6 = '.$variable.' AND g.field_3 = \'2\')
    OR
    (m.field_6 = '.$variable.' AND m.field_8 = \'1\' AND g.field_3 = \'1\')
    OR
    (g.field_4 = '.$variable.' AND g.field_3 = \'0\')';
    Run a test query and see what comes back. Let me know what you find.

  8. #8
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    Ok, I'll go ahead and do that.

    There is one other problem that you could maybe have a think about, I can think of a workaround, but I'm not sure it would work. Maybe you can just have a look and confirm.

    One of my conditions invovles something like this:

    PHP Code:
    if ($phpvariable == $phpvariable2 && $array->field 3) {} 
    Obviously putting that inside the query is a bit awkward.

    What I'm thinking is something like this:

    PHP Code:
    $query ' SELECT ....... '
             
    ' WHERE .... '
             
    ' OR .... '
             
    . if ($phpvariable == $phpvariable2) {
                  echo 
    'OR ....'
               
    }
             . 
    ' OR .... ' 
    Should this work?

    Thanks
    Last edited by deliriousthunder; 06-03-2009 at 04:07 AM. Reason: Mistake

  9. #9
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    Ok,

    So I figured out another way to achieve the same result, I just created 2 strings: $queryP1 and $query P2.

    $queryP2 was created as follows:

    PHP Code:
     if ($phpvariable1 == $phpvaribale2) {
             
    $queryP2 'OR(...)';
          } else {
             
    $queryP2 '';
          } 
    Then I just concatenated the strings together:

    PHP Code:
     $query $queryP1.$queryP2
    So it's more or less working now. There is still at least one issue though: duplicate entries appear to the end user under certain conditions. I need to figure out a way to either strip these from the array/not display them/filter them out using the query.

    The other thing is that the page loading time is still slow. I had just assumed that I was causing the problem. I was a bit confused by how long the query seemed to be taking, so I commented out my code and timed it.

    It takes 9.5s without my code , and 10.5 with. So I guess I haven't really slowed it down much, it was just really slow in the first place.

  10. #10
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    Re: Use a foreach statement to build an array

    First look into learning about tertiary (ternary) coding. You can then change your code as below:

    PHP Code:
    $query ' SELECT ....... '
             
    ' WHERE .... '
             
    ' OR .... '
             
    . (($phpvariable == $phpvariable2) ? 'OR ....' '')
             . 
    ' OR .... '
    As for the slow loading time, there are a TON of factors that can influence how long it takes to load a page. The first thing I always look at are the images, and the size of each one. There are very few times where an image on a web page should be over 50k in size.

    As a tool you can use to help you figure it out, there is an addon for Firefox called YSlow. It will analyze your page and give you recommendations on how to decrease your loading time.

    Other than that, you can get others to look at it and give you their opinions. What I have found though, is that it typically is not the fault of SQL queries as to the slow loading times (unless there a lot of very large queries). It is usually either a lot of data on the page or poor design.

    One other thing. When referencing fields in an array, the correct way to do it is:
    PHP Code:
    $array['field'
    or
    PHP Code:
    $array[0
    Hope this has helped.

  11. #11
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    Thanks.

    I'll have a look into tertiary coding.

    I'll try YSlow as well, but my hands are a little tied as far as changing things goes. It's a joomla based site, and I'm using a template from a third party, (which is not generally slow).

    I don't know if you've used joomla before, but I assume you'll understand what I'm talking about when I say that I'm modifying a third party component.

    Which also explains my somewhat strange way of referencing fields in an array, it's just standard practice in joomla. If I did it any other way I would just confuse myself, and anyone else who happens to read my code. Thanks for the tip though

  12. #12
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    Re: Use a foreach statement to build an array

    I understand perfectly. I didn't realize you were using a third-party solution. Even with Joomla, the page should not be taking that long to load.

  13. #13
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    Even with Joomla, the page should not be taking that long to load.
    I realise this, what I mean is that the template I'm using is not generally slow, so I think it's the component, (that I am modifying), itself which is causing the slow loading time. I doubt I will be able to do much to change how efficiently the component works, it's just too big to make it worthwhile. I'll have a look though, no harm in trying.

    As for filtering out duplicates in an array, I'm wondering if you have any suggestions. I understand why my query is producing duplicates, but it's a complicated thing to describe. If you are interested, I'll PM you the query with all the real field names in it, and try to explain what it's doing.

    Thanks

  14. #14
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    Re: Use a foreach statement to build an array

    Feel free to PM me if you would like. You can always try the UNIQUE keyword, as well as GROUP BY to try and get rid of the duplicates in your query.

    In regards to the component you are modifying, is it one that you have created from scratch, or one that was previously created and you are modifying to fit your needs?

  15. #15
    deliriousthunder's Avatar
    Junior Member

    Status
    Offline
    Join Date
    Feb 2009
    Posts
    29

    Re: Use a foreach statement to build an array

    PM sent (though I think I have solved it)

    It's a third party compononet by the way, but I have permission from the owner to modify it.

    Thanks,
    Tom



Page 1 of 2 1 2 Last

Tags for this Thread