How to get JSON id after item is created - php

Im using a function to share a collection of bookmarks with other users and i need to get the id after the new item is created in wordpress userpro bookmarks plugin
function share_collection($id,$name,$cbcolor,$user) {
$user_id = get_user_by( 'email', $user );
$user_id_current = get_current_user_id();
$collectionscurrent = $this->get_collections($user_id_current);
$collections = $this->get_collections($user_id->ID);
$collections[] = array('label' => $name);
// transfer bookmarks to shared collection
foreach($collectionscurrent[$coll_id] as $k => $arr) {
if ($k != 'label') {
$collections["This is where id should go"][$k] = 1;
}
}
update_user_meta($user_id->ID, '_wpb_collections', $collections);
}
How do i retrive the id created from $collections[] = array('label' => $name); and use it in the place where i mentioned "This is where id should go"
get_collections function is as follows
function get_collections($user_id) {
return (array)get_user_meta($user_id, '_wpb_collections', true);
}
Thanks in advance!

It's called array index. Assuming $collections is zero based numerical array without any "holes" in it (hole would be eg index 1 in [0 => 'a', 2 => 'b']), you can use:
$collections[] = array('label' => $name);
$idx = count($collections) - 1;
If it's not numerical or there can be holes, you have to figure out index to use first:
$idx = count($collections);
$collections[$idx] = array('label' => $name);

Related

CakePHP 3 fast insertion/updating of records

I am trying to insert/update +/- 10k rows with a foreach loop. The complete loop duration is about 3-5minutes. Are there any tips on my code to do the insertion of update faster? The $rows are retrieved from a xls file converted to domdocument.
foreach($rows as $key => $row)
{
if($key < 1){continue;}
$cells = $row -> getElementsByTagName('td');
foreach ($cells as $cell) {
$project_id = $cells[0]->nodeValue;
$title = $cells[1]->nodeValue;
$status = $cells[2]->nodeValue;
$projectmanager = $cells[3]->nodeValue;
$engineer = $cells[4]->nodeValue;
$coordinator = $cells[5]->nodeValue;
$contractor_a = $cells[6]->nodeValue;
$contractor_b = $cells[7]->nodeValue;
$gsu = $cells[9]->nodeValue;
$geu = $cells[10]->nodeValue;
$query = $this->Projects->find('all')->select(['project_id'])->where(['project_id' => $project_id]);
if ($query->isEmpty()) {
$project = $this->Projects->newEntity();
$project->title = $title;
$project->project_id = $project_id;
$project->status = $status;
$project->projectmanager = $projectmanager;
$project->engineer = $engineer;
$project->coordinator = $coordinator;
$project->contractor_a = $contractor_b;
$project->contractor_b = $contractor_a;
$project->gsu = date("Y-m-d H:i:s");
$project->geu = date("Y-m-d H:i:s");
$project->gsm = date("Y-m-d H:i:s");
$project->gem = date("Y-m-d H:i:s");
if ($this->Projects->save($project)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}else{
debug($project->errors());
}
}else{
continue;
$query->title = $title;
$query->status = $status;
$query->projectmanager = $projectmanager;
$query->engineer = $engineer;
$query->coordinator = $coordinator;
$query->contractor_a = $contractor_b;
$query->contractor_b = $contractor_a;
$query->gsu = $gsu;
$query->geu = $geu;
if ($this->Projects->save($query)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}
}
}
//$this->Flash->error(__('The project could not be saved. Please, try again.'));
}
For faster bulk inserts don't use entities but rather generate insert queries directly.
https://book.cakephp.org/3.0/en/orm/query-builder.html#inserting-data
Ello, my vriend.
The TableClass->save() method is useful when saving one single record, in your case, you should use TableClass->saveMany() instead.
For this to happen, you need to treat your entities as arrays inside your foreach.
After the foreach, you will use another method from the tableclass (newEntities) to convert the array into entities before finally save them.
Basic example:
//Lets supose our array after our foreach become something like this:
$all_records =
[
//Each item will be an array, not entities yet
[
'name' => 'I.N.R.I.',
'year' => '1987',
'label' => 'Cogumelo',
'country' => 'Brazil',
'band' => 'Sarcófago',
'line_up' => '[{"name":"Wagner Antichrist","role":"Vomits, Insults"},{"name":"Gerald Incubus","role":"Damned Bass"},{"name":"Z\u00e9der Butcher","role":"Rotten Guitars"},{"name":"D.D. Crazy","role":"Drums Trasher"}]'
],
//Another record coming in..
[
'name' => 'Eternal Devastation',
'year' => '1986',
'label' => 'Steamhammer',
'country' => 'Germany',
'band' => 'Destruction',
'line_up' => '[{"name":"Marcel Schmier","role":"Vocals, Bass"},{"name":"Mike Sifringer","role":"Guitars"},{"name":"Tommy Sandmann","role":"Drums"}]'
]
];
//Time to get the tableclass...
$albums = TableRegistry::get('Albums');
//Time to transform our array into Album Entities
$entities = $albums->newEntities($all_records);
//Now, we have transformed our array into entities on $entities, this is the variable we need to save
if(!$albums->saveMany($entities))
{
echo "FellsBadMan";
}
else
{
echo "FellsGoodMan";
}
You can read more about here

Assoc. Array, get Element with special id

I have the assoc array alldept.
I want now the 'name' element from the array with the id e.g. '1';
How do I access the id and output the 'name'?
The id is saved in $result[$i]['abteilung']
Thank you very much!
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt){
$alldept[] = array("id" => $singledpt->getId(),
"name" => $singledpt->getName()
);
}
As you are building this array yourself it would seem sensible to build it in a way that is later usable.
So why not build the array like this
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt) {
$alldept[ $singledpt->getId() ] = $singledpt->getName();
}
Now if you know you want the name of dept = 1 you just do
echo $alldept[1];
What I would suggest is to keep id as key and name as value:
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt){
$alldept[$singledpt->getId()] = $singledpt->getName();
}
Note: I am assuming getId will be unique
Then to fetch name, you can simply type $alldept[$id].
This might not be an answer, just an alternative. You can avoid a loop.

Get node from php array by one of the fields

I have an array with structure generated like this:
$groups = array();
while ($group = mysql_fetch_array($groups_result)) {
$groups[] = array( 'id' => $group['id'], 'name' => $group['name']);
}
How can I later in the code get the name of the group by its id? For example, I would like a function like:
function get_name_by_id($id, $array);
But I'm looking for some solution which is already implemented in PHP. I know it would be easier to make arrays with array[5] = array('name' => "foo") etc where 5 in this case is id, but in my code there is a lot of arrays already created like i mentioned above and I cannot easily switch it.
$groups = array();
while ($group = mysql_fetch_assoc($groups_result)) {
$groups[$group['id']] = array( 'name' => $group['name']);
}
$name = $groups['beer']['name'];
also please not using fetch_assoc is more efficient than fetch array
function get_name_by_id($id, $data) {
foreach($data as $d) {
if ($d['id'] == $id) {
return $d['name'];
}
}
// return something else, id was not found
}

Create array nested PHP

Hi all' I have a page into PHP where I retrieve XML data from a server and I want to store this data into an array.
This is my code:
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
array_push($hotel_array, $hotel_array2);
}
}
In this mode I have the array hotel_array which all hotel with rooms.
The problem is that: into my XML I can have multiple hotel with same ID (the same hotel) with same information but different rooms.
If I have an hotel that I have already inserted into my hotel_array I don't want to insert a new array inside it but I only want to take its rooms array and insert into the exisiting hotel.
Example now my situation is that:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
id = 1
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
[0]{
id = 1,
name = 'test'
rooms{
id = 30
}
}
}
I'd like to have this result instead:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
[0]{
id = 1
}
[1]{
id = 30
}
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
}
How to create an array like this?
Thanks
first thing is it helps to keep the hotel id as the index on hotel_array when your creating it.
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
if (!isset($hotel_array[$hotel_array2['id']])) {
$hotel_array[$hotel_array2['id']] = $hotel_array2;
} else {
$hotel_array[$hotel_array2['id']]['rooms'] = array_merge($hotel_array[$hotel_array2['id']]['rooms'], $hotel_array2['rooms']);
}
}
}
Whilst this is the similar answer to DevZer0 (+1), there is also quite a bit that can be done to simplify your workings... there is no need to use array_merge for one, or be specific about $i within your rooms array.
$hotels = array();
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string) $entry2->attributes()->HOTEL_CODE;
if ( empty($hotels[$id]) ) {
$hotels[$id] = array(
'id' => $id,
'name' => utf8_decode($entry2->HOTEL_NAME),
'rooms' => array(),
);
}
foreach($entry2->ROOM_DATA as $room){
$hotels[$id]['rooms'][] = array(
'id' => (string) $room->attributes()->CCHARGES_CODE;
);
}
}
}
Just in case it helps...
And this :)
$hotel_array = array();
foreach ($xml->DATA as $entry)
{
foreach ($entry->HOTEL_DATA as $entry2)
{
$hotel_code = (string) $entry2->attributes()->HOTEL_CODE;
if (false === isset($hotel_array[$hotel_code]))
{
$hotel = array(
'id' => $entry2->ID,
'code' => $hotel_code,
'name' => utf8_decode($entry2->HOTEL_NAME)
);
foreach($entry2->ROOM_DATA as $room)
{
$hotel['rooms'][] = array(
'id' => (string)$room->attributes()->CCHARGES_CODE,
);
}
$hotel_array[$hotel_code] = $hotel;
}
}
}

PHP - Help building a multi dimensional array

I would like to know how to get the values into this array. Can someone please help?
Each box whether it is the in or outbox should only be listed once and then have multiple ids associated with them. I need to be able to tell which id came from what box. The ids that are in the array are only samples.
$arr =
array(
'Inbox'=> array('id' => array(8, 9, 15)),
'Outbox'=> array('id' => array(8, 9, 15))
);
Thanks
$inbox = $db->Query("SELECT * FROM mail_inbox");
$outbox = $db->Query("SELECT * FROM mail_outbox");
foreach($inbox as $key => $array)
{
$output['Inbox']]['id'][] = $array['msg_seq'];
}
foreach($outbox as $key => $array)
{
$output['Outbox']]['id'][] = $array['msg_seq'];
}
print_r($output);
This will give me the db fields from the inbox but I have no idea how to get the outbox in there as well. I also get undefined index for ['Box']
Now that I know what you are saying, to input stuff, do something like this to input it into the array:
$ID = 9;
$box = "Inbox";
$arr[$box]['id'][] = $ID;
or
$IDs = array(9,5,13);
$box = "Inbox";
$array = array($box => $IDs);
or if you were getting it from a Database
$dbarray[0] = array('ID' => 9,
'Box' => 'Outbox');
foreach($dbarray as $key => $array)
{
$output[$array['Box']]['ids'][] = $array['ID'];
}
Multi deminsional arrays
The key or index is the first bracket
$array[key]="foo"
is the same as
$array = array('key' => 'foo');
if there is a second bracket, it of the array inside the value part of an array. IE
$array['key']['key2'] = "bar";
is the same as
$array = array('key' => array('key2' => 'bar'));
Basically, multideminsional arrays are just arrays inside of arrays.
foreach($arr as $box => $array)
{
echo $box;
// $box = The Box
foreach($array['ids'] as $ID)
{
echo $ID . ",";
// $ID = The ID
}
echo "<br>";
}
Sample:
Outbox 9,13,15,
Inbox 9,13,15,
This goes through each box, echos the box name, and each ID inside of the box, and echos the ID.
To access only one box
foreach($arr['Inbox'] as $ID)
{
echo $ID . ",";
}
Sample Output:
9,13,15,

Categories