Подмножество массива php
Мне нужно перейти от этого простого объекта:
SimpleXMLElement Object
(
[PubmedArticle] => Array
(
[0] => SimpleXMLElement Object
(
[MedlineCitation] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Owner] => NLM
[Status] => In-Process
)
[PMID] => 20538400
[DateCreated] => SimpleXMLElement Object
(
[Year] => 2010
[Month] => 07
[Day] => 08
)
[Article] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubModel] => Print-Electronic
)
[Journal] => SimpleXMLElement Object
(
[ISSN] => 1090-2147
[JournalIssue] => SimpleXMLElement Object
(
[@attributes] => Array
(
[CitedMedium] => Internet
)
[Volume] => 73
[Issue] => 3
[PubDate] => SimpleXMLElement Object
(
[Year] => 2010
[Month] => Aug
)
)
[Title] => Brain and cognition
[ISOAbbreviation] => Brain Cogn
)
[ArticleTitle] => Increased saccadic rate during smooth pursuit eye movements in patients at Ultra High Risk for developing a psychosis.
[Pagination] => SimpleXMLElement Object
(
[MedlinePgn] => 215-21
)
[Abstract] => SimpleXMLElement Object
(
[AbstractText] => Abnormalities in eye tracking are consistently observed in schizophrenia patients and their relatives and have been proposed as an endophenotype of the disease. The aim of this study was to investigate the performance of patients at Ultra High Risk (UHR) for developing psychosis on a task of smooth pursuit eye movement (SPEM). Forty-six UHR patients and twenty-eight age and education matched controls were assessed with a task of SPEM and psychiatric questionnaires. Our results showed that both the corrective and non-corrective saccadic rates during pursuit were higher in the UHR group. There were however no differences in smooth pursuit gain between the two groups. The saccadic rate was related to positive UHR symptoms. Our findings indicate that abnormalities in SPEM are already present in UHR patients, prior to a first psychotic episode. These abnormalities occur only in the saccadic system.
[CopyrightInformation] => 2010 Elsevier Inc. All rights reserved.
)
[Affiliation] => Department of Psychiatry, Academic Medical Center, University of Amsterdam, The Netherlands. [email protected]
[AuthorList] => SimpleXMLElement Object
(
[@attributes] => Array
(
[CompleteYN] => Y
)
[Author] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => van Tricht
[ForeName] => M J
[Initials] => MJ
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Nieman
[ForeName] => D H
[Initials] => DH
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Bour
[ForeName] => L J
[Initials] => LJ
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Boerée
[ForeName] => T
[Initials] => T
)
[4] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Koelman
[ForeName] => J H T M
[Initials] => JH
)
[5] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => de Haan
[ForeName] => L
[Initials] => L
)
[6] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Linszen
[ForeName] => D H
[Initials] => DH
)
)
)
[Language] => eng
[PublicationTypeList] => SimpleXMLElement Object
(
[PublicationType] => Journal Article
)
[ArticleDate] => SimpleXMLElement Object
(
[@attributes] => Array
(
[DateType] => Electronic
)
[Year] => 2010
[Month] => 06
[Day] => 09
)
)
[MedlineJournalInfo] => SimpleXMLElement Object
(
[Country] => United States
[MedlineTA] => Brain Cogn
[NlmUniqueID] => 8218014
[ISSNLinking] => 0278-2626
)
[CitationSubset] => IM
)
[PubmedData] => SimpleXMLElement Object
(
[History] => SimpleXMLElement Object
(
[PubMedPubDate] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubStatus] => received
)
[Year] => 2009
[Month] => 10
[Day] => 26
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubStatus] => revised
)
[Year] => 2010
[Month] => 4
[Day] => 28
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubStatus] => accepted
)
[Year] => 2010
[Month] => 5
[Day] => 12
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubStatus] => aheadofprint
)
[Year] => 2010
[Month] => 6
[Day] => 9
)
[4] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubStatus] => entrez
)
[Year] => 2010
[Month] => 6
[Day] => 12
[Hour] => 6
[Minute] => 0
)
[5] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubStatus] => pubmed
)
[Year] => 2010
[Month] => 6
[Day] => 12
[Hour] => 6
[Minute] => 0
)
[6] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubStatus] => medline
)
[Year] => 2010
[Month] => 6
[Day] => 12
[Hour] => 6
[Minute] => 0
)
)
)
[PublicationStatus] => ppublish
[ArticleIdList] => SimpleXMLElement Object
(
[ArticleId] => Array
(
[0] => S0278-2626(10)00059-X
[1] => 10.1016/j.bandc.2010.05.005
[2] => 20538400
)
)
)
)
[1] => SimpleXMLElement Object
(
[MedlineCitation] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Owner] => NLM
[Status] => MEDLINE
)
[PMID] => 19109059
[DateCreated] => SimpleXMLElement Object
(
[Year] => 2009
[Month] => 02
[Day] => 09
)
[DateCompleted] => SimpleXMLElement Object
(
[Year] => 2009
[Month] => 04
[Day] => 08
)
[Article] => SimpleXMLElement Object
(
[@attributes] => Array
(
[PubModel] => Print-Electronic
)
[Journal] => SimpleXMLElement Object
(
[ISSN] => 1872-8952
[JournalIssue] => SimpleXMLElement Object
(
[@attributes] => Array
(
[CitedMedium] => Internet
)
[Volume] => 120
[Issue] => 2
[PubDate] => SimpleXMLElement Object
(
[Year] => 2009
[Month] => Feb
)
)
[Title] => Clinical neurophysiology : official journal of the International Federation of Clinical Neurophysiology
[ISOAbbreviation] => Clin Neurophysiol
)
[ArticleTitle] => Quantification of the auditory startle reflex in children.
[Pagination] => SimpleXMLElement Object
(
[MedlinePgn] => 424-30
)
[Abstract] => SimpleXMLElement Object
(
[AbstractText] => Array
(
)
)
[AuthorList] => SimpleXMLElement Object
(
[@attributes] => Array
(
[CompleteYN] => Y
)
[Author] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Bakker
[ForeName] => Mirte J
[Initials] => MJ
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Boer
[ForeName] => Frits
[Initials] => F
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => van der Meer
[ForeName] => Johan N
[Initials] => JN
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Koelman
[ForeName] => Johannes H T M
[Initials] => JH
)
[4] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Boerée
[ForeName] => Thijs
[Initials] => T
)
[5] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Bour
[ForeName] => Lo
[Initials] => L
)
[6] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Tijssen
[ForeName] => Marina A J
[Initials] => MA
Для массива, который выглядит как:
Lastname (number of times)
Boerée (2)
Koelman (2)
Bour (2)
van Tricht (1)
Nieman (1)
de Haan (1)
Linzen (1)
Bakker (1)
Boer (1)
Tijssen (1)
van der Meer (1)
С уважением!
Первое, что мне нужно сделать, это получить все Last_names в одном массиве, это должно быть сделано с помощью цикла foreach:
foreach($xml->xpath('//AuthorList') as $AuthorList) {
foreach ($AuthorList->Author as $Author) {
//$author_last_name_list = $Author->LastName;
//$author_last_name_list .= $author_last_name_list;
$author_last_name_list join array($Author->LastName);
}
}
(это не работает)
но как мне построить массив в цикле foreach? 2-й, если у меня есть большой список имен, как мне получить новый массив с "сколько раз имя было в массиве"... С уважением!
2 ответа
Вот несколько примеров рекурсивных функций поиска по массиву: http://php.net/manual/en/function.array-search.php. Просто измените их так, чтобы они возвращали все найденные экземпляры в виде массива, а не только первое найденное совпадение. Удачи!:)
РЕДАКТИРОВАТЬ (может сработать на это...):
Я верю, что вы можете просто получить все Lastname
s SimpleXML, но давайте перейдем к тому, что у вас есть. Я думаю, что вы имеете в виду что-то вроде этого:
$author_last_name_list = array();
foreach($xml->xpath('//AuthorList') as $AuthorList) {
foreach ($AuthorList->Author as $Author) {
// $author_last_name_list join array($Author->LastName);
if (array_key_exists($Author, $author_last_name_list) {
$author_last_name_list[$Author] += 1;
} else {
$author_last_name_list[$Author] = 1;
}
}
}
Во-первых, если мой ответ на ваш предыдущий вопрос помог вам, тогда вы должны принять ответ.
Если мой код не работает, вы должны прокомментировать мой ответ и сказать мне, чтобы я мог исправить свой ответ.
Во-вторых, создание массива в цикле - это просто добавление значений в пустой массив:
$authors = array();
foreach ($xml->xpath('//AuthorList') as $AuthorList) {
foreach ($AuthorList->Author as $Author) {
$name = (string) $Author->LastName;
if(!array_key_exists($name, $authors)) {
$authors[$name] = 0;
}
$authors[$name] += 1;
}
}
А позже зациклиться $authors
, Ключи содержат имя и значение вхождения.
обновление: (потому что я хороший на этот раз;))
foreach($authors as $name=>$times) {
echo $name . "($times)" . "<br />"; // or PHP_EOL if you print it on a terminal
}
Узнайте больше о массивах в PHP.
Относительно вашего кода: даже если он не работает, короткое замечание:
$author_last_name_list = $Author->LastName;
$author_last_name_list .= $author_last_name_list;
При этом вы сначала устанавливаете переменную $author_last_name_list
в $Author->LastName
переопределяя значение, которое было в $author_last_name_list
до, а затем вы объединяете. То, что вы всегда получите, это:
$author_last_name_list = "A";
$author_last_name_list .= $author_last_name_list; // => 'AA';
Если вы хотите получить имена в строке (что вам здесь не поможет), вам придется инициализировать переменную перед циклом:
$author_last_name_list = '';
foreach($xml->xpath('//AuthorList') as $AuthorList) {
foreach ($AuthorList->Author as $Author) {
$author_last_name_list .= $Author->LastName;
}
}
А также
$author_last_name_list join array($Author->LastName);
неверный синтаксис PHP