tags:

views:

300

answers:

4

In a while loop I have:

$row = mysql_fetch_array($result)

Held under $row are two arrays which when shown using print_r display the following:

Array
(
[4] => Post Content
[value] => Post Content
)

Array
(
[4] => Post Title
[value] => Post Title
)

How can I choose "Post Content" and "Post Title" from the array without it being repeated in the while loop?

The original version of this question confused the duplication with the problem. The issue is how to extract the second array [value] when they are both held under $row.

+1  A: 

You want to make sure an array only has unique values? If that doesn't work with the arrays in an array, it's classic de-duping with a store of what you've already seen.

$dedupedValues = array()
foreach ($row as $items) {
    if (! is_set($dedupedValues[$items['value']])) {
        $dedupedValues[$items['value']] = true;  // we have this value
        echo "echo the title/value....";
    }

}

Another alternative is to improve the SQL that gets the data to begin with to avoid duplicates in the first place (see: MySQL 'DISTINCT')

Alister Bulman
+2  A: 

You can also make sure the values won't be insterted twice using mysql_fetch_assoc() or mysql_fetch_row().
Thus:

$row = mysql_fetch_assoc($result);
Array
(
['value'] => Post Content
)

Array
(
['value'] => Post Title
)
Pim Jager
+1  A: 

Pim Jager showed much better way of doing this, but if you insist on using mysql_fetch_array():

$i = 0;
$size = count($row);
if ($size > 0) {
  while ($i < floor($size / 2)) {
   ..... = $row[$i];
   $i += 1;
  }
}

Edit:

After reading again, I'm not sure if I quite understand the question.

If you have nested arrays for example:

$row = array('data1' => array('orange', 'banana', 'apple'),
             'data2' => array('carrot', 'collard', 'pea'));

And you want to access each array then:

$data1 = $row['data1'];
// = array('orange', 'banana', 'apple')
$data2 = $row['data2'];
// = array('carrot', 'collard', 'pea')
// OR
$orange = $row['data1'][0];
$banana = $row['data1'][1];
$apple = $row['data1'][2];
$carrot = $row['data2'][0];
// ... so on..

Taking that in account the loop looks like this:

$i = 0;
$size = count($row);
if ($size > 0) {
  while ($i < floor($size / 2)) {
   $something = $row['data1'][$i]; //Or $row[0][$i]; using your example
   $something = $row['data2'][$i]; //Or $row[1][$i]; using your example
   $i += 1;
  }
}

But I really suggest using mysql_fetch_assoc() and foreach loop, like in Pims Jagers example

Maiku Mori
A: 

Final solution was found by slightly restructuring the original query as per Topbit's suggestion and the use of two while loops.

while($row_title = mysql_fetch_array($result_title)){
$row_body = mysql_fetch_array($result_body);

    // code
}

Thank you to all those who suggested solutions.

nickcharlton