Echoing Array Result Format

Discussion in 'PHP' started by kampbell411, Jun 14, 2010.

  1. #1
    Hi, I just had a quick question on printing results in an a certain array.
    
    // While row = mysql object
    while($row = mysql_fetch_object($result))
    {
    	// $cat = $row->cat;
    	// $dog = $row->dog;
    	// $mice = $row->mice;
    	
    	// Create a new entry in the array.
    	$addresses[] = array(
    		'cat' => $row->cat,
    		'dog' => $row->dog,
    		'mice' => $row->mice
    	);
    }
    
    
    PHP:
    If I want the first rows 'cat' and 'mice'. Is this the correct way to write it:
    echo $addresses['0']['cat']['mice'];
     
    kampbell411, Jun 14, 2010 IP
  2. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #2
    They would each be their own hash within the array......

    So.....

    echo $addresses[0]['cat'];
    echo $addresses[0]['mice'];
    PHP:
     
    lukeg32, Jun 14, 2010 IP
  3. kampbell411

    kampbell411 Peon

    Messages:
    82
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Ah gotcha. I'll just separate them. Thanks!
     
    kampbell411, Jun 14, 2010 IP
  4. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #4
    You can concatenate them if you want to output them both; although it is better to seperate with a comma for multilple lists. Thats if I misunderstoof you and you wanted to do it on one line :)

    E.G

    <?php
    #more efficient / quicker
    echo $addresses[0]['cat'], ":", $addresses[0]['mice'];
    ?>
    PHP:
    Or, what seems to be the more common way

    <?php
    # slower, but used more commonly
    echo $addresses[0]['cat'] . ":" . $addresses[0]['mice'];
    ?>
    PHP:
     
    lukeg32, Jun 14, 2010 IP
  5. sijumpk

    sijumpk Peon

    Messages:
    24
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thats the correct way. One more thing is that its not needed this much code to create the array $addresses. just use

    while($addresses[] = mysql_fetch_assoc($result));
     
    sijumpk, Jun 15, 2010 IP
  6. gapz101

    gapz101 Well-Known Member

    Messages:
    524
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    150
    #6
    ^^ this is nice
     
    gapz101, Jun 15, 2010 IP
  7. roopajyothi

    roopajyothi Active Member

    Messages:
    1,302
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    80
    #7
    Right!
    if you use DB you can use this!

    else you can use echo $addresses[0]['mice']; and so
     
    roopajyothi, Jun 15, 2010 IP