Store array in Laravel 5.6 - arrays

I have to following array from inputs
array:9 [
"columns" => "4"
"device_id" => array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
"hub_id" => "11"
"usage" => array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
....
In my foreach loop i get back only one value not all
$devices = $request->all();
foreach ($devices["device_id"] as $device) {
dd($device);
}
This will return only 1 one value not all.
I have problem displaying all the value and saving them to database.
Witch would be the fast and the right way ?

The array and the behaviour you are getting is normal.
$devices = $request->all();
foreach ($devices["device_id"] as $device) {
dd($device);
}
This will indeed return 1, because your cursor is at the first value of $devices["device_id"]. If you wait for the next iteration, it'll be 2, then 3 and 4.
Remember you can also write your foreach this way:
foreach ($devices["device_id"] as $index => $device)
, where $index will be equal to the index related to the current value.
If you want all values, you can just simply dd($devices["device_id"]), it'll return you this array:
array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]

You do not save array in a database. Databases are not supposed to save multidimensional structures, since they do not support them.
You must convert your array into a format that the database is able to save, for example JSON or PHP serialize. It is actually very common to save data in this way if you do not need to search it easily at a later time.
Nevertheless, I would use a setter in your model to achieve this:
public function setAttributeNameAttribute($values)
{
$this->attributes['attribute_name'] = json_encode($values);
}
public function getAttributeNameAttribute($values)
{
return json_decode($values);
}

Related

How to order an array by bool values in laravel livewire

I have an array, I want to order that array by "is_available" key, (true first)
I'm using laravel 8 and a livewire component
0 => array:12 [▼
"id" => 1
"name" => "치킨 ~The Chicken~"
"is_available" => true
"nearest_customer_distance" => 4905.4423678942
"customers" => array:26 [▶]
]
1 => array:12 [▼
"id" => 2
"name" => "混ぜるな危険"
"is_available" => false
"customers" => array:10 [▶]
]
2 => array:12 [▼
"id" => 3
"name" => "Oh! Bánh mì"
"is_available" => true
"customers" => array:8 [▶]
]
3 => array:12 [▼
"id" => 5
"name" => "CHIJIMI DEVIL"
"is_available" => false
"customers" => array:44 [▶]
]
]
I'm trying this
$newFranchiseList = $this->getFranchiseListActualPage();
$finalFranchiseList = array_merge($this->franchiseList, $newFranchiseList);
$finalFranchiseList = collect($finalFranchiseList)->sortBy('is_available')->reverse();
$this->franchiseList = $finalFranchiseList->toArray();
but I get the order by ID in my view, this is my view
#forelse($franchiseList as $franchise)
#if($franchise['is_available'])
{{$franchise['name']}}
IS AVAILABLE
#else
{{$franchise['name']}}
NOT AVAILABLE
#endif
#empty
#endforelse
if I do a dump($this->franchiseList) the list is shown with the order of is_available!
note: $this->franchiseList is never used in the component, the only line to be used is the last one, if I don't use this line, the list is empty
component data collection process
first, in javascript call a livewire listener
window.livewire.emit('franchises:selectedCoords', JSON.stringify(selectedCoords));
then that is received by the component
public $selectedLatitude,
$selectedLongitude,
$perPage = 20,
$franchiseList = [],
$page = 1,
$totalFranchises = 0,
$isLoaded = false;
protected $listeners = [
'franchises:selectedCoords' => 'getCoords'
];
public function render()
{
return view('livewire.franchise-list');
}
public function getCoords($selectedCoords)
{
if ($selectedCoords) {
if (!empty($this->franchiseList)) {
$this->clearList();
}
$this->selectedLatitude = json_decode($selectedCoords, true)['lat'];
$this->selectedLongitude = json_decode($selectedCoords, true)['lng'];
}
$this->getFranchiseList();
}
public function getFranchiseList()
{
if ($this->selectedLatitude && $this->selectedLongitude) {
if (!$this->allFranchisesAreLoaded())
{
$newFranchiseList = $this->getFranchiseListActualPage();
$finalFranchiseList = array_merge($this->franchiseList, $newFranchiseList);
$this->franchiseList = collect($finalFranchiseList)->sortBy('is_available')->reverse()->toArray();
}
$this->isLoaded = true;
}
}
remember that $this->franchiseList is never overwritten, that is, it is only used once, in the line $this->franchiseList = collect($finalFranchiseList)->sortBy('is_available')->reverse()->toArray (); and if it is not done, it ends up being an empty array, so there is no other $this->franchiseList with the order shown by the blade view
Livewire will on each request serialize the public properties, so that it can be sent to the frontend and stored in JavaScript.
Now here's the kicker: JavaScript will do its own internal sorting on objects, which you can't prevent. So to work around that, you have to re-key your array after you sort it, so that the keys are now in ascending order of what you sorted it to.
Basically, all you need to do before you call ->toArray(), is to call ->values() on it, thereby grabbing the values in the order they were, and PHP will assign it new keys starting from 0.
$this->franchiseList = collect($finalFranchiseList)->sortBy('is_available')->reverse()->values()->toArray();
For example, a object like this in JavaScript,
{
1: 'foo',
0: 'bar',
}
Will be internally sorted by JavaScript like this
{
0: 'bar',
1: 'foo',
}
And you can't change that. That's why you need to re-key it.

How to get and split Array values in Laravel

Good day I need help on how to get the specific value on an array.I want to get the qty value and id value. The array output is like this
{"items":{"2":{"qty":1,"price":300,"item":{"id":2,"title":"LOTR","author":"James Cameron","price":300,"quantity":150,"created_at":"2020-08-24T13:35:36.000000Z","updated_at":"2020-08-24T13:38:52.000000Z"}}},"totalQty":1,"totalPrice":300}
As for the code
public function postCheckout(Request $request){
if (!Session::has('cart')){
return view('shop.shoppingcart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
$order = new Order();
$order->cart = json_encode($cart);
$order->address = $request->input('address');
$order->name = $request->input('name');
Auth::user()->orders()->save($order);
Session::forget('cart');
}
public function findvalarray(){
$order = Order::orderBy('created_at', 'desc')->limit(1)->get();
return view("test", ['order' => $order]);
}
The one with $order->cart = json_encode($cart) is the part where all the products that have been added to cart.
While the findvalarray is the one to find the cart value in the database dont mind the limit cause I need it for selection of a specific date.
And this is the blade view
#foreach($order as $item)
{{$item['cart']}}
#endforeach
Appreaciate the reply thank you
Your $order->cart is in JSON format you need to json_decode() your cart to convert it to array|object so you can access it's value, in your blade you can do
#foreach($order as $item)
{{ dd(json_decode($item['cart'])) }}
#endforeach
The result will be an object that you can access like json_decode($item['cart'])->totalQty
{#260 ▼
+"items": {#258 ▼
+"2": {#257 ▼
+"qty": 1
+"price": 300
+"item": {#251 ▼
+"id": 2
+"title": "LOTR"
+"author": "James Cameron"
+"price": 300
+"quantity": 150
+"created_at": "2020-08-24T13:35:36.000000Z"
+"updated_at": "2020-08-24T13:38:52.000000Z"
}
}
}
+"totalQty": 1
+"totalPrice": 300
}
If you want it as array you can do dd(json_decode($item['cart'], true)) this will give you
array:3 [▼
"items" => array:1 [▼
2 => array:3 [▼
"qty" => 1
"price" => 300
"item" => array:7 [▼
"id" => 2
"title" => "LOTR"
"author" => "James Cameron"
"price" => 300
"quantity" => 150
"created_at" => "2020-08-24T13:35:36.000000Z"
"updated_at" => "2020-08-24T13:38:52.000000Z"
]
]
]
"totalQty" => 1
"totalPrice" => 300
]
And you can access it like json_decode($item['cart'])['totalQty']

How to implode an array of arrays in Laravel?

Hi I have the following query:
$inc_quotes = DB::table('inc_quotes')->where('session_id', '=', $session_id)->get();
And it returns an array of arrays I believe like below:
array:36 [▼
0 => {#232 ▼
+"id": "5"
+"session_id": "1ee0556134d377c05673fce16f719b3e1077c797"
+"brand": "Acer"
+"drive": "Full Size Laptop"
+"screen": "Less than 2 Years old"
+"processor": "AMD A6"
+"condition": "No"
+"faults": "Light Damage,Heavy Damage"
+"price": "16.37"
+"name": "Alex"
+"lastname": "C"
+"email": "test#hotmail.com"
+"mobile": "12344567"
+"created_at": "2016-02-20 09:05:51"
+"updated_at": "2016-02-20 09:05:51"
}
1 => {#233 ▶}
2 => {#234 ▶}
Now I would like to extract from each array(row) for example the name and do a for each on the view to show the names for each row.
How can I extract the values?
I tried this
foreach($inc_quotes as $quote){
$quote_name = $quote->name;
}
But only returns the last value.
Any help much appreciated.
$quote_name = [];
foreach($inc_quotes as $key => $quote){
$quote_name[$key] = $quote->name;
}
EDITED
pass this to view like this.
return view('whateverYourView',compact('quote_name'));
and in view you access it with
#foreach($quote_name as $name)
{{ $name }}
#endforeach
Your $quote_name must be an array or an collection to receive all data that is comming from the array that you are iterating.
The $quote_name will be subscribed in every loop, that's why the method it will show only the last result.

references in perl: hash of array to another array

I have a problem with referencing a hash in an array to another array.
I have an array #result which looks like this:
#result = (
{ "type" => "variable",
"s" => "NGDP",
"variable" => "NGDP" },
{"type" => "subject",
"s" => "USA",
"subject" => "USA",
"variable" => "NGDP" },
{ "type" => "colon",
"s" => ",",
"colon" => "," },
{ "type" => "subject",
"s" => "JPN",
"subject" => "JPN",
"variable" => "NGDP" },
{ "type" => "operator",
"s" => "+",
"operator => "+" },
{"type" => "subject",
"s" => "CHN",
"subject" => "CHN",
"variable" => "NGDP" },
);
I want to divide this array into colons and push elements of the #result array to another array, so i wrote the script:
for ($i = 0; $i <= $#result; $i++) {
if (defined $result[$i]{subject} or $result[$i]{operator} and not defined $result[$i]{colon}) {
push #part_col, \%{$result[$i]};
}
elsif ($i == $#result) {
push #part_col_all, \#part_col;
}
elsif (defined $result[$i]{colon}) {
push #part_col_all, \#part_col;
my #part_col;
}
}
So what I need is that if I print out $part_col_all[0][0]{subject} the result will be "USA",
and for $part_col_all[1][0]{subject} will be "JPN",
and for $part_col_all[1][1]{operator} will be "+" etc.
My result for $part_col_all[0][0]{subject} is "USA"
and for $part_col_all[0][1]{subject} is "JPN" which should be in $part_col_all[1][0]{subject}.
The result for $part_col_all[0][3]{subject} is "CHN", while it should be in $part_col_all[1][2]{subject}.
I'm making an application which is creating graphs from economical data based on a certain economical input. The #result array is my preprocessed input where I know to which country which variable belongs. If I get an input like GDP USA CAN, JPN+CHN I need to split this input to GDP USA CAN and JPN+CHN. That's why I made a condition, if colon is found, push everything in #part_col to the first element of #part_col_all, and then if it's on the end of the input, push JPN+CHN to the second element of #push_col_all.
So #part_col_all should looks like this:
#part_col_all = (
(
{"type" => "subject",
"s" => "USA",
"subject" => "USA",
"variable" => "NGDP" },
{"type" => "subject",
"s" => "CAN",
"subject" => "CAN",
"variable" => "NGDP" },
),
(
{ "type" => "subject",
"s" => "JPN",
"subject" => "JPN",
"variable" => "NGDP" },
{ "type" => "operator",
"s" => "+",
"operator" => "+" },
{"type" => "subject",
"s" => "CHN",
"subject" => "CHN",
"variable" => "NGDP" },
)
);
I dont know what I'm doing wrong. Sorry if there are any basic mistakes, im a beginner. Thanks a lot.
First, you're missing a quote:
{ "type" => "operator",
"s" => "+",
"operator" => "+" },
^ missing
As for printing, you can do the following:
foreach my $part (#part_col){
print $part->{operator}."\n";
}
Or do whatever you want in the print cycle with the values
You should read the Perl Reference Tutorial to help you.
There's no sin in dereferencing to simplify your code:
my #part_col;
my #part_col_all;
for $i ( 0..$#array ) {
my %hash = ${ $result[$i] }; # Make it easy on yourself. Dereference
if ( defined $hash{subject} or defined $hash{operator} and not defined $hash{colon} ) {
push #part_col, \%hash; # or push, #par_col, $result[$i]
}
}
Notice I changed the for from the three part setup you had to a cleaner and easier to understand way of stating it.
Looking closer at your data structure, I notice that $hash{type} will tell you whether or not $hash{operator}, $hash{subject}, or $hash{colon} is defined. Let's just use $hash{type} and simplify that if:
my #part_col;
my #part_col_all;
for my $i ( 0..$#array ) {
my %hash = ${ $result[$i] }; # Make it easy on yourself. Dereference
if ( $hash{type} eq "subject" or $hash{type} eq "operator" ) {
push #part_col, \%hash; # or push, #par_col, $result[$i]
}
}
In fact, since #array is just an array, I'll treat it like one. I'll use a simple for structure to go through each element of my array. Each element is a hash_reference, so:
for my $hash_ref ( #array ) {
my %hash = %{ %hash_ref };
if ( $hash{type} eq "subject" or $hash{type} eq "operator" ) {
push #part_col, \%hash;
}
}
And further simplification, I can dereference and talk about a particular element of my hash all at once by using the -> syntax:
for my $hash_ref ( #array ) {
if ( $hash_ref->{type} eq "subject" or $hash_ref->{type} eq "operator" ) {
push #part_col, $hash_ref;
}
}
I'm trying to understand the rest of your code:
elsif ($i == $#result) {
push #part_col_all, \#part_col;
}
elsif (defined $hash_ref->{colon}) {
push #part_col_all, \#part_col;
my #part_col;
}
}
These pushes of #part_col onto #part_col_all confuse me. Exactly what are you trying to store in #part_col_all? Remember that \#part_col is the location in memory where you're storing #part_col. You're pushing that same memory location over and over onto that hash, so you're storing the same reference over and over again. Is that really what you want? I doubt it.
You need to do is to decide exactly what your data structure really represents. A data structure should have a solid definition. What does the data structure #part_col_all represent? What does the data structure $part_col_all[$i] represent? What does the data structure $part_col_all[$i]->[$j] represent? Without knowing this, it's very hard to answer the rest of your question.
Are you storing elements where the type is colon in one array and everything else in another array? Or are you storing everything in one array, and in another array, storing everything that's not a type colon?
Once I understand this, I can answer the rest of your question.
Addendum
Thank you for your reply, I will try that way and write my results. It is realy helpful. I updated my question with more information about data structure of #part_col_all. I hope that you understand what I'm trying to explain, if not I'll try it again.
If I understand what you're doing, someone enters in NGDP USA , JPN+CNA and that means you're comparing the NGDP between the United States vs. Japan and China combined.
It seems to me that you would want three separate variables:
$parameter - What you are measuring. (GDP, etc.)
#countries_set_1 - The first set of countries
#countries_set_2 - The second set of countries which you're comparing against the first set.
And, what you call the colon (which we would call a comma in the U.S.) as a separator between the first set of countries vs. the second set. Then, you'd simply go through a loop. It could be that the two arrays are merely two elements of the same array, and the sets of countries are array references. I imagine something like this:
#input = qw(GDP USA, JPN CHN); # Compare the GDP of the USA with Japan and China together
my $parameter = shift #input; # Remove what you're measuring
my #country_sets; # An array of arrays
my $set = 0 # Which set you're on
for my $value ( #input ) {
if ( $value eq "," ) {
$set += 1; # Next Set
next;
}
push #{ $country_sets[$set] }, $input;
}
This would create a data structure like this:
#country_sets = (
(
USA,
),
(
JPN,
CHN,
),
)
No need for the complex #results since you're only going to have a single operation (GDP, etc.) for all involved.
However, I think I see what you want. We'll go with an array of arrays. Here's what I had before:
for my $hash_ref ( #array ) {
if ( $hash_ref->{type} eq "subject" or $hash_ref->{type} eq "operator" ) {
push #part_col, $hash_ref;
}
}
We'll combine that and the code I offered right above which splits the countries into two sets:
my #country_sets; # An array of arrays
my $set = 0 # Which set you're on
for my $country_ref ( #array ) {
next if $country_ref->{type} eq "variable"; # We don't want variables
if ( $country_ref{type} eq "colon" ) { # Switch to the other country set
set += 1;
next;
}
push #{ $country_sets[$set] }, $country_ref;
}
The first few entries will go into $country_sets[0] which will be an array reference. After the colon (which won't be input into the set), the second set of countries will go into $country_sets[1] which will be an other array_ref to a reference of hashes:
#country_sets - Contains the input information into two sets
#country_sets[$x] - A particular set of countries (and possibly operator)
#country_sets[$x]->[$y] - A Particular country or operator
#country_sets[$x]->[$y]->{$key} - A particular value from a particular country
Where $x goes from 0 to 1. This will give you something like this:
$country_sets[0] = (
{
"type" => "subject",
"s" => "USA",
"subject" => "USA",
"variable" => "NGDP",
},
)
$country_sets[1] = (
{
"type" => "subject",
"s" => "JPN",
"subject" => "JPN",
"variable" => "NGDP",
},
{
"type" => "operator",
"s" => "+",
"operator => "+",
},
{
"type" => "subject",
"s" => "CHN",
"subject" => "CHN",
"variable" => "NGDP",
},
);

codeigniter insert multiple rows by selected checkboxes

I'm having an issue if somebody could help would be much appreciated.
<input type="checkbox" name="symbols[]" value="1" />
.... and this line repeats 10-15 times with a different value
model
$data = array(
array('symbol_id' => $this->input->post('symbols'))
);
return $this->db->insert_batch('symbols', $data);
now my problem is that is inserting only first value of the selected checkbox (in this case 1) and ignores everything else without inserting a new row of other checkboxes (like value 3, 5 and 9).
Could you suggest me some options ?
note: want i want to achieve is to insert a new row for each checkbox, so i can join another table which holds the symbols images (the values of checkboxes representing the id's of images).
If you have any other way around of how I could do this is very welcomed.
Thank you
edit: this is var_dump:
array(7)
{
[0] => string(1) "8"
[1] => string(1) "9"
[2] => string(2) "10"
[3] => string(2) "11"
[4] => string(2) "12"
[5] => string(2) "13"
}
The data is being sent as an array of active values, so if you would check 1,3,5,10,20, in your $this->input->post('symbols'); array you will have array(1, 3, 5, 10, 20):
function InsertSymbols() {
$data = array();
foreach($this->input->post('symbols') as $symb) {
$data[] = array('symbol_id' => $symb);
}
return $this->db->insert_batch('symbols', $data);
}
This code is for CI but you can use it in core as well just put insert query with in your foreach.
$symbol_arr = $this->db->escape_str($this->input->post('symbols'));
foreach ($symbol_arr as $k=> $val) {
$DataARR = array(
"symbol" => $val,
"created" => date('Y-m-d h:i:s A'),
);
$this->common_model->insert_batch($DataARR);
}

Resources