喜欢
A
Alpha
Aloo
Amakeaviral
B
Boki
Bone
我的数据来自数据库,在数组中。 我需要数组中的第一个字符。
我试过了:
$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone");
for($i = 0; $i <= count($my_array); $i++){
$first_char = $my_array[$i]{0};
echo $first_char;
}
但这不太好用。 我怎么能这样做?
答案 0 :(得分:7)
尝试将substr()
简称为
$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone");
foreach($my_array as $v){
echo substr($v, 0, 1);
}
或您的代码: - 从循环=
中移除<=
(否则您会收到通知)并使用[]
而不是{}
$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone");
for($i=0; $i < count($my_array); $i++){
$first_char = $my_array[$i][0];
echo $first_char;
}
答案 1 :(得分:3)
寻找第一个角色
substr("Hello", 0, 1); //output "H"
尝试:
$first_char = substr($my_array[$i], 0, 1);
完整代码:
for($i = 0; $i < count($my_array); $i++){
echo $first_char = substr($my_array[$i], 0, 1);
}
注意:$i <= count($my_array)
应为$i < count($my_array)
答案 2 :(得分:3)
希望这对你有用 -
$my_array = array("Alpha","Aloo","Amakeaviral","Boki","Bone");
$newArray = array();
foreach($my_array as $value) {
$first_char = $value[0];
if (!empty($newArray)) {
$flag = false;
foreach ($newArray as $key => $val) {
if ($first_char == $key){
$newArray[$key][] = $value;
$flag = true;
}
}
if (!$flag) {
$newArray[$first_char][] = $first_char;
$newArray[$first_char][] = $value;
}
} else {
$newArray[$first_char][] = $first_char;
$newArray[$first_char][] = $value;
}
}
var_dump($newArray);
与上述相同但缩短了代码:
$my_array = array("Alpha","Aloo","Amakeaviral","Boki","Bone");
$newArray = array();
foreach($my_array as $value) {
if (empty($newArray[$value[0]])){
$newArray[$value[0]][]=$value[0];
}
$newArray[$value[0]][] = $value;
}
var_dump($newArray);
答案 3 :(得分:2)
基本上,每个字符串都是一个数组,可以像它一样访问:
$str = 'This is a string';
echo $str[0]; // Output: T
echo $str[1]; // Output: h
echo $str[2]; // Output: i
只需改变一下:
$first_char = $my_array[$i]{0};
进入这个:
$first_char = $my_array[$i][0];
答案 4 :(得分:2)
试试这个
$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone");
foreach($my_array as $v){
echo $v[0];
}
答案 5 :(得分:1)
请试试这个:
$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone");
for($i = 0; $i < count($my_array); $i++){
$first_char = $my_array[$i][0];
echo $first_char;
}
答案 6 :(得分:1)
我知道这有点旧了我很抱歉,但这就是我用一系列对象做的事情。我想在字母表中显示每个对象的标题。我使用了以下内容:
$items = array
(
[0] => stdClass Object
(
[title] => Alpha
[name] => Joe Blogs
[address] => 123 Harry Street
)
[1] => stdClass Object
(
[title] => Bravo
[name] => Jane Doe
[address] => 456 Upton Street
)
[2] => stdClass Object
(
[title] => Charlie
[name] => Jane Doe
[address] => 456 Upton Street
)
)
然后在辅助类
中声明此函数public static function alphaSortItems ($items) {
$sortedItems = array();
foreach ($items as $item) {
$sortedItems[$item->title[0]][] = $item;
}
return $sortedItems;
}
然后显示它们我用
<?php $sortedItems = Helper::alphaSortItems($this->items); ?>
<?php foreach ($sortedItems as $key => $value) : ?>
<h2><?php echo $key; ?></h2>
<?php foreach ($value as $item) : ?>
<h3><?php echo $item->title; ?></h3>
<?php endforeach; ?>
<?php endforeach; ?>
无论如何,我是怎么做到的: - )