Store array response as object inside array for options - php

I would like to been appending objects to instagram value instead of overwriting them if there is a new object that isn't repeated.
So I have this piece of code:
if (is_array($api_return)) {
$api_return += ['last_updated' => time()];
$this->instagram->set_user_id($api_return['user_id']);
$this->instagram->set_username($api_return['username']);
$this->instagram->set_access_token($api_return['access_token']);
$this->instagram->set_access_token_expiration($api_return['access_token_expiration']);
$this->instagram->set_last_updated($api_return['last_updated']);
// Show our authenticated message.
$page_content .= $this->get_admin_notice_content('green',
'auth-finished', $this->instagram->get_username());
update_option('instagram', $api_return);
}
What this does, is it takes $api_return which is a array and groups it into an object and saves it inside the database as this:
We have option_name which is instagram and then the value is:
a:5:{s:8:"username";s:16:"saint";s:7:"user_id";i:17841404774727369;s:12:"access_token";s:141:"IGQVJVR1N*****";s:23:"access_token_expiration";i:1650688769;s:12:"last_updated";i:1645536110;}
What I'm attempting to do:
Now I want to be able to save multiple object where the instagram key doesn't get overwritten but each new api_return gets stored as a new object if it's not the same in an array.
Here is an example:
authenticated_users = [
{s:8:"username";s:16:"saint";s:7:"user_id";i:17841404774727369;s:12:"access_token";s:141:"IGQVJVR1N*****";s:23:"access_token_expiration";i:1650688769;s:12:"last_updated";i:1645536110;}
{s:8:"username";s:16:"test3";s:7:"user_id";i:17841404774727369;s:12:"access_token";s:141:"IGQVJVR1N*****";s:23:"access_token_expiration";i:1650688769;s:12:"last_updated";i:1645536110;}
];
What is the best approach on storing the option value as an array with multiple objects?

You have to first load the option an then manually merge the values:
$current = get_option("instagram", []);
$newData = [
$api_return,
];
// Merge array $current and $newData into single array so
// $api_return is appended to $current and the option is updated.
update_option("instagram", array_merge($current, $newData));

Related

How to fetch values from the constant files and store it inside an array in php?

I have one constant file which contains all the status details ,i want to fetch the values from the constant file and store it inside an array in the form of indexed array, can you give me some idea how to do this one..
BooksConstants.php
class BooksConstants{
const PAID = 'settled';
const BOOK_FAILED_STATUSES = [
self::cancelled_by_customer,
self::FAILED,
self::FAILED_BY_GATEWAY,
self::INVALID_OTP
];
const BOOK_SUCCESS_STATUSES = [
self::PAID,
self::SUCCESS,
self::ON_THE_WAY,
self::PROGRESS
];
}
Controller.php
$array=[];
array_push($array,BooksConstants::BOOK_SUCCESS_STATUSES);
array_push($array,BooksConstants::BOOK_FAILED_STATUSES);
it's storing 0th index with all data for BOOK_SUCCESS_STATUES array and 1st index is storing for BOOK_FAILED_STATUES but my requirement is
$array=['failed','settled','failed by gateway'....);
Using array_push you will actually push an array to the 0th-index and after that push another array to the 1st-index.
As stated in the comment, array_merge() can be used here instead, as it will just place the content of the arrays besides each other in the returned array.
$array = array_merge(BooksConstants::BOOK_SUCCESS_STATUSES, BooksConstants::BOOK_FAILED_STATUSES);

Adding values to array in a loop

Iam working on a laravel project which stores values to a DB entry in loop on meeting certain conditions.
This first creates an array if the entry is for the first time and adds a value to it. Henceforth, it recalls the array and keeps adding values to it.
if(is_null($lead->shown_to)) {
$a = array();
array_push($a, "lead 1");
$lead->shown_to = serialize($cart);
$lead->save();
} else {
$a=unserialize($lead->shown_to);
array_push($a, "lead 2");
$lead->shown_to = serialize($a);
$lead->save();
}
To be able to create an array and add distinct elements to it repeatedly.
Is there a way to first check if the element exists in it or not. If it does, just move ahead, else add it?
Thanks in advance.
There're a couple of methods you can use.
You can first look for the value on the DB if exists using a column from the database like:
$result = Model::where( 'column', 'value' );
if ( $result ) {
// update already exists
} else {
// create one
}
// Retrieve flight by name, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
// Retrieve by name, or instantiate...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
Also it depends what you are looking for as firstOrCreate persists the value into the DB where firstOrNew just creates a new instance where you need to call save()
to check a value exists in an array you can use array_search(). this will return the value if exists. if not it returns false.
if(!array_search('lead 2', $a)) {
// array does't has 'lead 2' so,
array_push('lead 2', $a);
}
In Laravel I would take advantage of the Collections because they have a lot of helpful methods to work with.
I would do something like this:
OPTION 1
//Depending on the value of $lead->show, initialize the cart variable with the serialization of the attribute or and empty array and transform it to a collection.
$cart = collect($lead->shown_to ? unserialize($lead->shown_to) : []);
//Ask if the collection doesn't have the given value. If so, added it.
if (!$cart->contains($your_value)) {
$cart->push($your_value);
}
//Convert to array, serialize and store
$lead->shown_to = serialize($cart->toArray());
$lead->save();
OPTION 2
//Depending on the value of $lead->show, initialize the cart variable with the serialization of the attribute or and empty array and transform it to a collection.
$cart = collect($lead->shown_to ? unserialize($lead->shown_to) : []);
//Always push the value
$cart->push($your_value);
//Get the unique values, convert to an array, serialize and store
$lead->shown_to = serialize($cart->unique()->toArray());
$lead->save();
You can get more creative using the collections and they read better on Laravel
I think you can use updateOrCreate, if not exists it will create now, if exists, it will update it, so you can keep assigning value to shown_to property
$lead= App\Lead::updateOrCreate(
['name' => 'Lead 1'],
['shown_to' => serialize($a)]
);
if you wan to keep the existing shown_to better to use json data, so that you can do like
$lead= App\Lead::updateOrCreate(
['name' => 'Lead 1'],
['shown_to' => json_encode(array_push(json_decode($a), $newData))]
);

Wordpress output to array in query from custom field

I have created a custom field named "sec1array" in my categories so that i can add an array, for example 1,2,3,4
I want to retrieve that array and output it in the loop, so I created this code.
$seconearray = array($cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);
However, it only seems to be outputting the first post in the array. Is it something to do with the way the comma is outputting?
If I print $seconearray it outputs correctly, example 1,2,3,4
What you are doing is storing a string value of "1,2,3,4" in your database which when you are trying to construct an array from it like array("1,2,3,4") you end up just assigning a single value to that new array. This is why it only contains a single value.
You need to store your value in a serializable format so it can be converted back to an array after you save it to the database. There are many ways to do this, I'm sure others will give more examples:
JSON encode it
json_encode(array(1,2,3,4)); // store this in your db
json_decode($cat_data['sec1array']); // outputs an array
Or, you can use PHP serialize
serialize(array(1,2,3,4)); // store this in your db
unserialize($cat_data['sec1array']); // outputs an array
If you want to keep your string, you can explode it:
explode(',', $cat_data['sec1array']); // outputs your array of 1,2,3,4.
Using any of these methods will work. Finally you'll end up with an example like:
$seconearray = explode(',', $cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);

Laravel returning null value with where method (if variable is passed)

I'm trying to use a where method in laravel query. i have a string containing two values (separated by comma). I need to search with value that is after the comma. So i used explode php function to make an array . So I get an array containing two key-value pairs. i want to use 2nd value to search database. So i'm storing the second value in a variable and then passing that variable in the where method. But it's returning blank collection object
Here's the code
$vehicles_name_trim_ar = explode(',', Input::get('vehicles_name_trim'));
print_r of $vehicles_name_trim_ar is
Array
(
[0] => A3
[1] => 2.0T Premium Automatic
)
//storing both values in seperate variable
$model_name = $vehicles_name_trim_ar[0];
$model_trim = $vehicles_name_trim_ar[1];
$model = Model::where('model_trim', $model_trim)->get();
It's returning blank result. However if i'm proving static value, it return the result
$model = Model::where('model_trim', "2.0T Premium Automatic")->get();
What am i doing wrong?
You have a space at the start of the second value. try this:
$model_name = trim($vehicles_name_trim_ar[0]);
$model_trim = trim($vehicles_name_trim_ar[1]);

Navigating a returned object

In PHP I have a multidimensional object created from looping through a list of ids
$summary = array();
foreach ( $request->id as $id ) {
...
$summary[] = $summary_data;
}
it's then passed to my javascript.
return json_encode(array('summary' => $summary));
Not sure how to navigate the returned object correctly. Do I have to use the original list of id's, and use that as an index against this object? Or is there a better way to keep track of this?
End result, I want a select box such that when a new item is selected, its data is displayed.
A general JSON object would look like this (trying to put all possible cases):
{
"key1":"value1",
"subObject":{
"subKey1":"subValue1",
"subKey2":"subValue2"
},
"arrayOfSubObjects":[
{"subKey3":"subValue3"},
{"subKey4":"subValue4"}
]
}
You can reference any element of a JSON object with jsonObject.key, but remember those part between [] are arrays so you'll need to index them as if they were in an array so:
// to point subKey1:
jsonObject.subObject.subKey1;
// to point subKey3
jsonObject.arrayOfSubObjects[0].subKey3;
OR
// to point subKey1:
jsonObject["subObject"]["subKey1"];
// to point subKey3
jsonObject["arrayOfSubObjects"][0]["subKey3"];
note the 0 has no quotes because it's an index.

Categories