|
|
 |
key (PHP 3, PHP 4 , PHP 5) key -- 从结合数组中取得键名 说明mixed key ( array array)
key() 返回数组中当前单元的键名。
例子 1. key() 例子 |
<?php
$array = array (
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple'
);
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br>';
}
next($array);
}
?>
|
|
参见 current() 和 next()。
php at snr-graphics dot com
24-Mar-2001 03:50
A Method of Multi-Dimensionalizing an Associative Array (This idea was
designed with Graphics (image filenames in mind):
(A quick
overview):
While working on a rather large web application, I found
that I needed a way to obtain "all" the details on images used by
the application, these images (by filename) were stored in the
configuration file, in the form of associative arrays.
The
following represents an example of how I tool those and converted them into
multi-dimensional associative arrays.
<code sample
begin>
do {
$size =
getImageSize($path.$myarray[key($myarray)]);
if ($size[2] == '1') {
$size[2] = 'gif'; }
else if ($size[2] == '2') { $size[2] = 'jpg';
}
else if ($size[2] == '3') { $size[2] = 'png'; }
else if
($size[2] == '4') { $size[2] = 'swf'; }
else { $size[2] = 'UNKNOWN';
}
$myarray[key($myarray)] =
Array($myarray[Key($myarray)],$size[0],$size[1],$size[2],$size[3]);
}
while (next($myarray));
</end code sample>
The end
result is an multi-dim. associative array which contains the
values:
$myarray["this"][0] =
filename.gif
$myarray["this"][1] =
width
$myarray["this"][2] =
height
$myarray["this"][3] = type (converted to the file
extension.)
$myarray["this"][4] = height=x
width=x
This may not be all that impressive to some, but it turned
out to be very useful for me, so I thought I'd share, in addition, I think
it gives a "very" good example of "a use" for the Key()
function.
Frankly, I was quite happy to discover this function, I
can't count the number of times I "needed to use the key as a
value".
I hope you find this code useful.
| |