[英]how can i get value of two consecutive value of string array
I want to sort elements of an array which have string values (word) according to word length. 我想根据单词长度对具有字符串值(单词)的数组元素进行排序。 I am performing insertion sort:
我正在执行插入排序:
$str="welcome to php";
$st=explode(" ",$str);
$a=count($st);
for($i=0;$i<$a;$i++)
{
for($j=0;$j<$a;$j++)
{
if(strlen($st[$j])<strlen($st[$j+1]))
{$t=$st[$j];
$st[$j]=$st[$j+1];
$st[$j+1]=$t;}
}}
So the problem is $st[$j+1]
. 所以问题是
$st[$j+1]
。 It doesn't get next value of array. 它不会获得数组的下一个值。 It gives undefined offset.
它给出了未定义的偏移量。 How can I get next value of array?
我如何获得数组的下一个值?
Somthing like this should work for you: 这样的事情应该为您工作:
<?php
function lengthSort($a, $b){
return strlen($b) - strlen($a);
}
$str = "welcome to php";
$st = explode(" ", $str);
usort($st,'lengthSort');
var_dump($st);
?>
Output: 输出:
array(3) {
[0]=>
string(7) "welcome"
[1]=>
string(3) "php"
[2]=>
string(2) "to"
}
Also as Nick J
suggested take a look at the foreach loop! 就像
Nick J
建议的一样,看看foreach循环! It's very powerful! 非常强大!
You can define your own comparison function using php's usort
function. 您可以使用php的
usort
函数定义自己的比较函数。
See http://php.net/manual/en/function.usort.php 参见http://php.net/manual/en/function.usort.php
So all you have to do is write your own function that compares strings by their length, then call usort
and pass in your function. 因此,您要做的就是编写自己的函数,该函数按字符串的长度比较字符串,然后调用
usort
并传入函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.