Re: Newb question about getting keys/values from a single array element

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, Oct 08, 2009 at 06:08:48PM -0700, Daevid Vincent wrote:

> I feel like a total newb asking this, but I'm just having a brain fart or
> something...
> 
> I'm writing a page where I can either get back a list of items:
> 
> 	Array {
> 	  [1233] => "apple",
> 	  [6342] => "apricot",
> 	  [2345] => "banana",
> 	  ...
> 	}
> 
> where the user then refines it by choosing one single item and a single
> element array is returned like this:
> 
> 	Array {
> 	  [8575] => "peach",
> 	}
> 
> How can I get this $item so I can print it like so:
> 
> 	echo "The ID is $id and the name is $name";
> 
> Normally with an array of items, I do a:
> 
> 	foreach ($item as $id => $name) echo...
> 
> But that seems overkill for this scenario.
> 
> The rub is that I don't know the "id", so I can't use $item[0], and I also
> don't have something like $item['name'] to use either.
> 
> There's got to be an easy way to extract those.
> 
> 	list($id, $name) = $operator;
> 
> Felt like it would work for a minute (wishful thinking).

If you don't know the index, then you really have no choice but to
iterate through the POST array (if I understand you correctly). One
problem I see is that you're using an integer for your index. The way I
normally do things like this is to provide a prefix for the index. Like
this:

$items = array('fruit_1233' => 'apple',
    'fruit_6342' => 'apricot',
    'fruit_2345' => 'banana',
    'fruit_8575' => 'peach');

Then, out of all the POST members returned, I can pick out the ones
pertaining to fruit by simply looking for ones which have the 'fruit_'
prefix as their index. It tends to be clunky, but it's the only way I've
found to make it work:

$fruits = get_fruits_from_table();
foreach ($fruits as $key => $value) {
    $index = 'fruit_' . $key;
    if (isset($_POST[$index])) {
        echo "The user wants fruit #$key, $value.";
    }
}

Paul

-- 
Paul M. Foster

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux