In my very simple Laravel livewire component i have an array and when i try to add another data into that by clicking on a simple for example div i get fresh array with the last inserted data into that and i cant keep this array reference to append something data into that
<div wire:click="addNewSize"></div>
class SellerStoreNewProductComponent extends Component
{
public array $productSizes=[];
//...
public function addNewSize()
{
/* SOLUTION ONE */
//$this->productSizes[] = $this->productSizes + [str::random(10) => str::random(10)];
/* SOLUTION TWO */
//$this->productSizes[][]=array_push($this->productSizes, [str::random(10) => str::random(10)]);
/* SOLUTION THREE */
//array_push($this->productSizes, [str::random(10) => str::random(10)]);
dd($this->productSizes);
}
}
thanks in advance
If you're looking to add a key value pair to an existing array, you most likely want to use array_merge rather than array_push.
array_merge combines two arrays into a single array whereas array_push adds elements to an existing array.
public function addNewSize()
{
$this->productSizes = array_merge(
$this->productSizes, [Str::random(10) => Str::random(10)]
);
}
your current approaches will add a new index with new array data (previous value plus new value). so you just have to add new index to the array.
$this->productSizes['myKey'] = "myValue";
Related
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));
I have a Laravel site I am modifying, but there are some parts of the PHP code I don't quite understand, which are "array objects" or "object arrays". You see, I don't even know what to call them and so can't find a tutorial or basic data on it. Below is the code that I am dealing with:
private function parseMetric($result, $view)
{
$data = collect([]);
$result->each(function($item) use ($data, $view) {
if (isset($item->metric->{$view})) {
$data->push((object)[
'label' => $item->metric->{$view},
'value' => $item->metric->count
]);
}
});
...
From what I can tell, this creates an object out of $result. If I json_encode this and echo it out I get this:
[{"label":"1k-25k","value":14229},
{"label":"1mm+","value":1281},
{"label":"25k-50k","value":398},
{"label":"50k-75k","value":493},
{"label":"75k-100k","value":3848},
{"label":"100k-150k","value":9921},
{"label":"150k-200k","value":4949},
{"label":"200k-250k","value":3883},
{"label":"250k-300k","value":2685},
{"label":"300k-350k","value":2744},
{"label":"350k-500k","value":4526},
{"label":"500k-1mm","value":8690}]
Now this is obviously an array of arrays... or is it? Is it an array of objects? Or is it an object containing arrays? But the most important question is, how do I access and move or change the individual objects/arrays in this object? For example, I want to take the second object/array, which is:
{"label":"1mm+","value":1281}
and move it to the end. How do I do that? How do I find it? I used the following piece of code to find it which is pretty clunky:
$pos = strpos(json_encode($result), '1mm+');
if($pos){
Log::debug('Enrich 73, I found it!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
And once I find it, how do I move that array/object to the end of the whole object?
And finally, where can I find some kind of tutorial, or documentation, that describes this construct and how to work with it?
There is no need to json_encode the data. Since the data is an instance of Laravel Collection, you can manipulate it like so
$item = $data->firstWhere('label', '1mm+'); // get the item
$data = $data->filter(fn($value, $key) => $value->label !== '1mm+') // remove $item from $data
->push($item); // move $item to the end of data
Acording to Laravel documnentation for Collections, you can try something like this :
To find index of element with name = "1mm+" :
$index = $datas->search(function ($item, $key) {
return $item['name'] == "1mm+";
});
to get an element at a given index :
$element = $datas->get($index);
to Move element at index 3 to the end :
$index = 3
$elementToMove = $data->splice($index, 1);
$datas->push($elementToMove);
Here is a link to the document used : https://laravel.com/docs/8.x/collections
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);
This might seem super easy but to me its not, I have the following method:
public function addRadioButtonTab($groupName, $radioButtonTab)
{
$radioButtonTab = new RadioButtonTab($radioButtonTab);
$this->radioButtonTabs[][$groupName] = $groupName;
$this->radioButtonTabs[][] = $radioButtonTab;
}
I want to push the $radioButtonTab into the same array that contains the key: $groupName.
Right now I get two separate arrays, one with the key=>value and one with the object.
instead of looping and doing complex things try this:
public function addRadioButtonTab($groupName, $radioButtonTab)
{
$radioButtonTab = new RadioButtonTab($radioButtonTab);
$this->radioButtonTabs[][$groupName] = array($groupName, $radioButtonTab);
}
You should make an array of the values you want first, then append that to $this->radioButtonTabs.
public function addRadioButtonTab($groupName, $radioButtonTab)
{
$radioButtonTab = new RadioButtonTab($radioButtonTab);
// Just append arrays into the main array
$this->radioButtonTabs[] = array('group_name' => $groupName, $radioButtonTab);
// Or if you want your array to use `$groupName` as a key
$this->radioButtonTabs[$groupName] = array('group_name' => $groupName, $radioButtonTab)
}
Storing an array submitted from forms stores elements with null values. Is there a way to store only non null fields into the php array?
$_SESSION['items'] = $_POST['items'];
is my current code.
You should take a look at array_filter(). I think it is exactly what you are looking for.
$_SESSION['items'] = array_filter($_POST['items']);
# Cycle through each item in our array
foreach ($_POST['items'] as $key => $value) {
# If the item is NOT empty
if (!empty($value))
# Add our item into our SESSION array
$_SESSION['items'][$key] = $value;
}
Like #Till Theis says, array_filter is definitely the way to go. You can either use it directly, like so:
$_SESSION['items'] = array_filter($_POST['items']);
Which will give you all elements of the array which does not evaluate to false. I.E. you'll filter out both NULL, 0, false etc.
You can also pass a callback function to create custom filtering, like so:
abstract class Util {
public static function filterNull ($value) {
return isset($value);
}
}
$_SESSION['items'] = array_filter($_POST['items'], array('Util', 'filterNull'));
This will call the filterNull-method of the Util class for each element in the items-array, and if they are set (see language construct isset()), then they are kept in the resulting array.