开发者

usort returns undefined index

开发者 https://www.devze.com 2023-01-29 10:50 出处:网络
I have a multi dimensional array called \"soldier\": Array ( [0] => Array ( [name] =>开发者_运维技巧 Saiga 20k Semi

I have a multi dimensional array called "soldier":

Array
(
    [0] => Array
        (
            [name] =>开发者_运维技巧 Saiga 20k Semi
            [target] => 100
            [star] => gold
        )

[1] => Array
    (
        [name] => SVU Snaiperskaya Short
        [target] => 85
        [star] => gold
    )

[2] => Array
    (
        [name] => Type 88 Sniper
        [target] => 56
        [star] => gold
    )

I am trying to sort the array by the "target" value. I am using:

usort($soldier,'compare_target');

function compare_target($x,$y)
{
    if($x['target'] == $y['target'])
    {
        return 0;
    }
    elseif($x['target'] < $y['target'])
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

But PHP is throwing the following error: "Undefined index: target" for the 2 lines inside the function, any ideas?


function compare_target($x,$y)
{
    if ( !(isset($x['target']) && isset($y['target'])) ) 
        return 0;

    if ($x['target'] == $y['target'])
        return 0;
    elseif ($x['target'] < $y['target'])
        return 1;
    else
        return -1;
}

It's always bad style to assume something would be there. If you want to use $x['target'] you must check that it is valid to begin with, or you have a lingering bug.


yep sorry guys I did some dumping of $x and $y inside the function as suggested and it was an issue with some array elements in $soldier due to my own fault, I will delete this question, sorry for wasting your time!!

0

精彩评论

暂无评论...
验证码 换一张
取 消