开发者

Manipulating multidimensional array in PHP?

array(2) {
  [0]=>
  object(stdClass)#144 (2) {
    ["id"]=>
    string(1) "2"
    ["name"]=>
    string(5) "name1"
  }
  [1]=>
  object(stdClass)#145 (2) {
    ["id"]=>
    string(1) "4"
    ["name"]=>
    string(5) "name2"
  }
}

I want to add开发者_运维百科 key and value (for example [distance] = 100;) to the objects in the array. After this I want to sort on the distance values. How can I achieve this?


To get structure such as yours you can do:

$arr = array();
$arr[0]->id = "2";
$arr[0]->name = "name1";
$arr[1]->id = "4";
$arr[1]->name = "name2";

To add "distance" you can do:

$arr[0]->distance = 100;
$arr[1]->distance = 200;

To sort you can use decorate/sort/undecorate pattern:

$arr = array_map(create_function('$o', 'return array($o->distance, $o);'), $arr); // transform array of objects into array of arrays consisted of sort key and object
sort($arr); // sort array of arrays
$arr = array_map('end', $arr); // take only last element from each array

Or you can use usort() with custom comparison function like this:

function compareDistanceFields($a, $b) {
  return $a->distance - $b->distance;
}
usort($arr, "compareDistanceFields");


$my_array[0]->distance = 100;
$my_array[0]->distance = 101;

usort($my_array, "cmp");
function cmp($a, $b)
{
   if ($a->distance == $b->distance)
     return 0;
   return ($a->distance > $b->distance) ? 1: -1;
}


What you have here is an array of hashes; that is, each element of your array is a hash (a structure containing elements, each of which is identified by a key).

In order to add a key and value, you just assign it, like this:

$array[0]["distance"]=100;
$array[1]["distance"]=300;
#and so on

PHP hashes and arrays in general are documented here.

Now, in order to sort your array (each of whose elements is a hash), you need to use the "uasort" function, which allows you to define a comparison function; in this comparison function you define the behavior you want, which is sorting on the value of the distance key.

Something like this:

// Comparison function, this compares the value of the "distance" key
// for each of the two elements being compared.
function cmp($a, $b) {
    if ($a["distance"] == $b["distance"]) {
        return 0;
    }
    return ($a["distance"] < $b["distance"]) ? -1 : 1;
}

Once this is defined, you call uasort like this:

uasort($array, 'cmp');

Find more documentation on uasort here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜