Sly Sly - 29 days ago 6
PHP Question

How to assign new keys to a PHP associative array

I have this PHP that creates an array of jobs as $jobs. However I'd like the keys to be [ref] rather than 0, 1, 2 etc

$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);
}


The array created is:

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
)

)


But I would like the keys to be

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
)

)


How can I do this?

Answer

Change this:

array_push($jobs, $item);

to this:

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