Push an object on to an array containing the same key - php

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)
}

Related

Accumulate strings and array values into an array as a class property via method

I have a class with method add() that accepts strings and arrays. I need to have an array with all users, but I cannot seem to get it. All I get is multiple arrays with all users. How could I merge those arrays into one?
class Users {
function add($stringOrArray) {
$arr = array();
if(is_array($stringOrArray)) {
$arr = $stringOrArray;
} else if(is_string($stringOrArray)) {
$arr[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($arr);
}
When I use this test:
public function testOne() {
$users = new Users();
$users->add('Terrell Irving');
$users->add('Magdalen Sara Tanner');
$users->add('Chad Niles');
$users->add(['Mervin Spearing', 'Dean Willoughby', 'David Prescott']);
This is what I get, multiple arrays but I need one array.
Array
(
[0] => Terrell Irving
)
Array
(
[0] => Magdalen Sara Tanner
)
Array
(
[0] => Chad Niles
)
Array
(
[0] => Mervin Spearing
[1] => Dean Willoughby
[2] => David Prescott
)
You can cut a lot of unnecessary bloat from your method.
You can cast ALL incoming data to array type explicitly. This will convert a string into an array containing a single element. If the variable is already an array, nothing will change about the value.
Use the spread operator (...) to perform a variadic push into the class property.
Code: (Demo)
class Users
{
public $listOfUsers = [];
function add($stringOrArray): void
{
array_push($this->listOfUsers, ...(array)$stringOrArray);
}
}
$users = new Users;
$users->add('Terrell Irving');
$users->add(['Magdalen Sara Tanner', 'Chad Niles']);
$users->add(['Mervin Spearing']);
var_export($users->listOfUsers);
Output:
array (
0 => 'Terrell Irving',
1 => 'Magdalen Sara Tanner',
2 => 'Chad Niles',
3 => 'Mervin Spearing',
)
All you need is to store the added users in a class property, for example $listOfUsers.
If adding the array you use the array_merge() function otherwise just add new user at the end of indexed array.
<?php
class Users {
// here will be all the users stored
public $listOfUsers = array();
function add($stringOrArray) {
//$arr = array();
if(is_array($stringOrArray)) {
// merge two arrays - could create duplicate records
$this->listOfUsers = array_merge($this->listOfUsers, $stringOrArray);
} else if(is_string($stringOrArray)) {
// simply add new item into the array
$this->listOfUsers[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($this->listOfUsers);
}
}
In your example you are storing the data locally within the method add() and it is not kept for future usage. This behavior is corrected using the class property $listOfUsers that can be accesed using $this->listOfUsers within the class object and if needed outside of the class.

Keeping array reference and adding something into that

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";

Cannot use object of type stdClass as array when looping with array

I'm trying to get Count of a table called TestRunList that has the foreign key the same as another table called Testrun meaning i want to get count of how many testrunlist that single testrun has in the same page i did a forloop to get testrun id for each testrunlist but it didn't seem to work i get this error
Cannot use object of type stdClass as array
heres my Code in the controller
$data = DB::table('TestRun')->get();
$runs=array();
for ($i=0;$i<sizeof($data);$i++)
{
$testrunID=$data[$i]['TestRunID'];
$Testrunlist=TestRunList::where('test_run_id',$testrunID)->count();
$runs[$i]=[
'Countruns'=>$Testrunlist
];
}
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
$data is a Collection, you can't access using array syntax
$data = DB::table('TestRun')->get();
$runs = [];
$data->each(function ($row) use ($runs) {
$runs[] = [
'Countruns' => TestRunList::where('test_run_id',$row-> TestRunID)->count()
];
});
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
Always use
print_r($data);
if it's object run echo $data->username if array run echo $data['username'];
So you know what type of data you're dealing with.

How to create array of objects in php

I'm attempting to create an array of objects in php and was curious how I would go about that. Any help would be great, thanks!
Here is the class that will be contained in the array
<?php
class hoteldetails {
private $hotelinfo;
private $price;
public function sethotelinfo($hotelinfo){
$this->hotelinfo=$hotelinfo;
}
public function setprice($price){
$this->price=$price;
}
public function gethotelinfo(){
return $hotelinfo;
}
public function getprice(){
return $price;
}
}
And here is what I am attempting to do-
<?PHP
include 'file.php';
$hotelsdetail=array();
$hotelsdetail[0]=new hoteldetails();
$hotelsdetail[0].sethotelinfo($rs);
$hotelsdetail[0].setprice('150');
?>
The class attempting to create the array doesn't compile but is just a best guess as to how I can do this. Thanks again
What you should probably do is:
$hotelsDetail = array();
$details = new HotelDetails();
$details->setHotelInfo($rs);
$details->setPrice('150');
// assign it to the array here; you don't need the [0] index then
$hotelsDetail[] = $details;
In your specific case, the issue is that you should use ->, not .. The period isn't used in PHP to access attributes or methods of a class:
$hotelsdetail[0] = new hoteldetails();
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
Note that I capitalized the class, object, and function names properly. Writing everything in lowercase is not considered good style.
As a side note, why is your price a string? It should be a number, really, if you ever want to do proper calculations with it.
You should append to your array, not assign to index zero.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
This will append the object to the end of the array.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
This would create an array with three objects, appending each one successively.
Additionally, to correctly access an objects properties, you should use the -> operator.
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
You can get the array of object by encoding it into json and decoding it with $assoc flag as FALSE in json_decode() function.
See the following example:
$attachment_ids = array();
$attachment_ids[0]['attach_id'] = 'test';
$attachment_ids[1]['attach_id'] = 'test1';
$attachment_ids[2]['attach_id'] = 'test2';
$attachment_ids = json_encode($attachment_ids);
$attachment_ids = json_decode($attachment_ids, FALSE);
print_r($attachment_ids);
It would render an array of objects.
output:
Array
(
[0] => stdClass Object
(
[attach_id] => test
)
[1] => stdClass Object
(
[attach_id] => test1
)
[2] => stdClass Object
(
[attach_id] => test2
)
)

html form arrays how to store into php array not including null elements

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.

Categories