views:

1009

answers:

1

I have a query to get all the compatible phones in a specific country, and in my controller I'm using Set::extract to reduce the untidy result array to just an array of product names.

$results = $this->Country->compatiblePhones($country); $compatiblePhones = Set::extract('/p/product_name',$results); $this->set('compatiblePhones',$compatiblePhones);

The extract tidies this result:

Array
(
    [0] => Array
        (
            [p] => Array
                (
                    [product_name] => Bat Phone
                )

        )

    [1] => Array
        (
            [p] => Array
                (
                    [product_name] => Premium Phone
                )

        )

    [2] => Array
        (
            [p] => Array
                (
                    [product_name] => Brick Phone
                )

        )
    [3] => Array
        (
            [p] => Array
                (
                    [product_name] => Satellite Phone
                )

        )

)

to this:

Array
(
    [0] => Bat Phone
    [1] => Premium Phone
    [2] => Brick Phone
    [3] => Satellite Phone
)

I pass this array to my view and have a bit of code that shows links for each phone in the array:

<ul>
  <?php echo (in_array("Bat Phone", $compatiblePhones)) ?    '<li><a href="#">Bat Phone</a></li>'    : '' ;?>
  <?php echo (in_array("Premium Phone", $compatiblePhones)) ?   '<li><a href="#">Premium Phone</a></li>'   : '' ;?>
  <?php echo (in_array("Brick Phone", $compatiblePhones)) ?    '<li><a href="#">Brick Phone</a></li>'    : '' ;?>
  <?php echo (in_array("Satellite Phone", $compatiblePhones)) ? '<li><a href="#">Satellite Phone</a></li>' : '' ;?>
</ul>

This is my problem: The satellite phone is always going to be returned as it works everywhere, but I only want to have it shown exclusively if none of the other phones work at all. I suppose I could do this using in_array() on the view side, but its messy enough as it is.

How could I use the Set:: functionality in my controller to manipulate the array before I send it to my view? I have also considered that if the array contains the exact correct phones, I can just foreach them in my view, instead of having the messy in_array() setup.

Thank you.

+4  A: 

Well if you know that the name will always be "Satellite Phone":

$otherPhones = Set::extract('/p[product_name!=Satellite Phone]/product_name', $results);

Will get you all the phones except the satellite phone. Then you can do this in your view:

<ul>
<?php
foreach ( /* loop through "other" phones */ )
{
    // echo them
}

if (empty($otherPhones))
{
    // echo the satellite phone
}
?>
</ul>

But I suppose, if you know that it will always be "Satellite Phone" you can just not fetch it from the database and it will be far more efficient..

dr Hannibal Lecter