Jump to content

comparing WireArray


ngrmm
 Share

Recommended Posts

I would like to create pages from a json feed.
So i decode my json and create them via API.

$jsonData = json_decode($jsonFromOtherWebsite);

foreach($jsonData as $jsonDataItem) {
	$pageTitle = $jsonDataItem->name;			
	$p = new Page();
	$p->template = 'import_page';
	$p->parent = $pages->get(xxxx);
	$p->title = $pageTitle;
	$p->save();
}

Let's say the source (json) changes and i have to do another import.
Then I want to compare the new json with the existing pages to see if there are new ones and if there some aren't there anymore.

Is there a way to compare the new JsonData with my existing pw-pages with the API.
Something like

foreach($jsonData as $jsonDataItem) {
	// check if a page with this title exist
	if($pages->find("template=import_page, title=$jsonDataItem->name") {
		// update existing field values
		$getExistingPage = $pages->find("template=import_page, title=$jsonDataItem->name");
		// update value
		$getExistingPage->setAndSave('field', $jsonDataItem->x);
	}
	else {
		// create new page
		$pageTitle = $jsonDataItem->name;			
        $p = new Page();
        $p->template = 'import_page';
        $p->parent = $pages->get(xxxx);
        $p->title = $pageTitle;
        $p->save();	
	}
}

// search for pages wich are not anymore in the json and hide/delete them
// …

 

Link to comment
Share on other sites

$import_timestamp = time();

foreach($jsonData as $jsonDataItem) {
	// Search for the page
	$imported_page = $pages->findOne("template=import_page, title=$jsonDataItem->name");
	// Check if the page exist
	if ($imported_page->id) {
		// update values
		$imported_page->setAndSave([
        	'field_A' => $jsonDataItem->source_A,
        	'field_B' => $jsonDataItem->source_B,
        	'field_C' => $jsonDataItem->source_C
        ]);
	} else {
		// create new page
        	$p = new Page();
        	$p->template = 'import_page';
        	$p->parent = $pages->get(xxxx);
        	$p->title = $jsonDataItem->name;
        	$p->save();
	}

}

// use this because if the pages were not updated/created during this import it means they don't come in the json
$old_imported_pages = $pages->findMany("template=import_page, modified<$import_timestamp");
// hide/delete all $old_imported_pages..
  

 

Edited by Pixrael
setAndSave optimization with array
  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...