我的目标是创建一个Objets数组(文章),我设法恢复pmid, doi and title
但是当涉及到数组location
时,我无法做到,这就是代码我尝试过:
<?php
class Article
{
private $pmid;
private $doi;
private $title;
private $location=array();
public function setLocations($tabLocations){
foreach ($tabLocations as $key => $value) {
$location[]=$value;
}
}
public function setPmid($_pmid){
$this->pmid=$_pmid;
}
public function setDoi($_doi){
$this->doi=$_doi;
}
public function setTitle($_title){
$this->title=$_title;
}
//getters
public function getTitle(){
return $this->title;
}
}
//get pmid from DOM
require_once "simple_html_dom.php";
$html=new simple_html_dom();
$html->load_file('http://brainspell.org/search?query=psen+1');
$pmid=array();
foreach ($html->find('.paper-stuff') as $article) {
$pmid[]= str_replace("/article/","",$article->find('a',0)->getAttribute('href'));
}
//Create ALLArticles TAb
$articlesTab=array();
//upload data file
$json=file_get_contents("C:\wamp\www\projet1\json\allArticles.json");
$data=json_decode($json,true);
foreach ($pmid as $tabPmid) {
foreach ($data as $key=>$value) {
if($value["pmid"]==$tabPmid)
{
$details=new Article();
$details->setPmid($value["pmid"]);
$details->setDoi($value["doi"]);
$details->setTitle($value["title"]);
$details->setLocations($value['experiment']['location']);
$articlesTab[]=$details;
}
}
}
?>
我的JSON代码的一部分:
{
"papers": {
"paper": [
{
"pmid": "6330179",
"doi": "10.1002/cne.902260203",
"experiment": [
{
"id": "12789",
"location": [
"-46.0,-80.0,2.0",
"-42.0,-76.0,-2.0",
"44.0,-72.0,-2.0",
"52.0,-68.0,-6.0",
"-32.0,-88.0,4.0",
"-32.0,-90.0,8.0",
"34.0,-82.0,8.0",
"34.0,-78.0,8.0",
"-30.0,-52.0,-12.0",
"-30.0,-52.0,-10.0",
"28.0,-66.0,-16.0",
"26.0,-66.0,-12.0",
"-46.0,-76.0,6.0",
"-46.0,-78.0,0.0",
"46.0,-70.0,4.0",
"48.0,-74.0,0.0"
]
}
]
},
{
"pmid": "10022492",
"doi": "10.1093/cercor/9.1.20",
"experiment": [
{
"id": "258",
"location": [
"-42.0,26.0,20.0",
"-36.0,30.0,16.0",
"-30.0,32.0,0.0",
"-28.0,14.0,48.0",
"-20.0,8.0,56.0",
"-32.0,4.0,52.0",
"50.0,10.0,36.0",
"48.0,24.0,20.0",
"32.0,0.0,56.0",
"8.0,-2.0,64.0",
"4.0,-8.0,68.0",
"-16.0,-4.0,12.0",
"-2.0,-18.0,12.0",
"-8.0,2.0,8.0",
"-44.0,-28.0,32.0",
"-4.0,-60.0,60.0",
"36.0,-58.0,52.0"
]
},
如果有人可以帮助我。提前谢谢:D
答案 0 :(得分:0)
如果您发现location是另一个数组,那么为了获得它的所有元素,它就需要被破坏。所以尝试这样的事情。
$details->setLocations(implode(",",$value['experiment']['location']));
这会将数组打印为以逗号分隔的字符串;也许你可以选择你想要的分隔符。
答案 1 :(得分:0)
您只是错过$this
来引用setLocations
public function setLocations($tabLocations){
foreach ($tabLocations as $key => $value) {
$this->location[]=$value; // $this->location is where you want to store your locations
}
}
顺便说一句,我认为没有必要在你的setter中迭代$ tabLocations。不会
public function setLocations($tabLocations){
$this->locations = $tabLocations;
}
也可以做到这一点?
或者如果你想摆脱钥匙:
public function setLocations($tabLocations){
$this->locations = array_values($tabLocations);
}