質問

I want to store the following pieces of information in a structure or array of some sort in PHP;

  • URL
  • Title
  • Description
  • Rank

I want the data to be associative, that a particular URL refers to a Title, Description & Rank.

I want to be able to sort the data then by rank, then echo it in that order, with each element still being associated.

Should I use associative arrays? Structs? Or some other PHP data structure?

Thanks

役に立ちましたか?

解決

$urls["http://example.com"] = array(
    "rank" => 3,
    "title" => "abc",
    ...
)

and use uasort for ordering

他のヒント

I would create a custom class for this. For more information about php classes, visit php.net manual.

You can try :

$data = new LinkData();

$data->set("http://stackoverflow.com/q/17406624/1226894", [
        "name" => "Data Structure",
        "rank" => 3
]);

$data->set("http://stackoverflow.com/", [
        "desc" => "Nice Site",
        "title" => "Stackoverflow"
]);

foreach($data as $v) {
    print_r($v);
}

Output

Array
(
    [url] => http://stackoverflow.com/q/17406624/1226894
    [title] => 
    [rank] => 3
    [desc] => 
    [name] => Data Structure
)
Array
(
    [url] => http://stackoverflow.com/
    [title] => Stackoverflow
    [rank] => 
    [desc] => Nice Site
)

Class Used

class LinkData implements IteratorAggregate {
    private $data = array();

    function getIterator() {
        return new ArrayIterator($this->data);
    }

    function set($url, array $info) {
        $this->data[md5($url)] = array_merge([
                "url" => $url,
                "title" => null,
                "rank" => null,
                "desc" => null
        ], $info);
    }

    function get($url) {
        return isset($this->data[$key = md5($url)]) ? $this->data[$key] : [];
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top