公告
财富商城
积分规则
提问
发文
2019-01-10 18:13发布
来,给爷笑一个
If I have:
$array = array( 'one' =>'value', 'two' => 'value2' );
how do I get the string one back from $array[1] ?
one
$array[1]
Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,
function get_key($array, $index){ $idx=0; while($idx!=$index && next($array)) $idx++; if($idx==$index) return key($array); else return ''; }
$array = array( 'one' =>'value', 'two' => 'value2' ); $keys = array_keys($array); echo $keys[0]; // one echo $keys[1]; // two
You don't. Your array doesn't have a key [1]. You could:
[1]
Make a new array, which contains the keys:
$newArray = array_keys($array); echo $newArray[0];
But the value "one" is at $newArray[0], not [1]. A shortcut would be:
$newArray[0]
echo current(array_keys($array));
Get the first key of the array:
reset($array); echo key($array);
Get the key corresponding to the value "value":
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1] doesn't correspond to "one" any which way you turn it.
Or if you need it in a loop
foreach ($array as $key => $value) { echo $key . ':' . $value . "\n"; } //Result: //one:value //two:value2
You might do it this way:
function asoccArrayValueWithNumKey(&$arr, $key) { if (!(count($arr) > $key)) return false; reset($array); $aux = -1; $found = false; while (($auxKey = key($array)) && !$found) { $aux++; $found = ($aux == $key); } if ($found) return $array[$auxKey]; else return false; } $val = asoccArrayValueWithNumKey($array, 0); $val = asoccArrayValueWithNumKey($array, 1); etc...
Haven't tryed the code, but i'm pretty sure it will work.
Good luck!
$array = array( 'one' =>'value', 'two' => 'value2' ); $allKeys = array_keys($array); echo $allKeys[0];
Which will output:
最多设置5个标签!
Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,
You don't. Your array doesn't have a key
[1]
. You could:Make a new array, which contains the keys:
But the value "one" is at
$newArray[0]
, not[1]
.A shortcut would be:
Get the first key of the array:
Get the key corresponding to the value "value":
This all depends on what it is exactly you want to do. The fact is,
[1]
doesn't correspond to "one" any which way you turn it.Or if you need it in a loop
You might do it this way:
Haven't tryed the code, but i'm pretty sure it will work.
Good luck!
Which will output: