如何将新键分配给PHP关联数组

时间:2016-11-05 14:23:06

标签: php arrays

我有这个PHP,它创建了一系列作业作为$ jobs。但是我希望键是[ref]而不是0,1,2等

$xml_feed = new DOMDocument();
$xml_feed->load('http://jobs.recruitsosimple.com/job/762/xml');
$jobs = array();
foreach ($xml_feed->getElementsByTagName('job') as $node) {
    $item = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'ref' => $node->getElementsByTagName('referencenumber')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('url')->item(0)->nodeValue,
        );
    array_push($jobs, $item);
}

创建的数组是:

Array
(
    [0] => Array
        (
            [title] => Theatre Nurse
            [ref] => MT29
            [link] => http://jobs.com/job/1192/29
        )

    [1] => Array
        (
            [title] => Ward Nurse
            [ref] => MT39
            [link] => http://jobs.com/1192/762/39
        )

)

但我希望关键是

Array
(
    [MT29] => Array
        (
            [title] => Theatre Nurse
            [ref] => MT29
            [link] => http://jobs.com/job/1192/29
        )

    [MT39] => Array
        (
            [title] => Ward Nurse
            [ref] => MT39
            [link] => http://jobs.com/1192/762/39
        )

)

我该怎么做?

1 个答案:

答案 0 :(得分:1)

改变这个:

array_push($jobs, $item);

到此:

$jobs[$item['ref']] = $item;