PHP remove item from array - php

I know how to remove something from an array but in this case its a bit different. My code seems to generate this annoying item in the array called "*items", I'm not sure how to remove it.
I need it removing because my application visually displays all the data in the array and right now there's just a blank space because of this item.
My code
Basically in my code I have converted an object to an array like this
$accounts = Account::where('archive', false)->select('id', 'display_name')->get();
$accounts = (array) $accounts;
I'm 100% sure its to do with this. is there a way to remove the "*items" item from the array?
I've tried
array_pop($array);
this didn't work for me it just removed the last item before "*item"
unset($array['*item']);
This also didn't work, it just didn't unset anything at all.
Picture
EDIT
I'm working on someone else's code here and there is a lot of random features and functions, writing and explaining the whole script would take a silly amount of time so I tried to include what I thought would be necessary.

Casting your object with (array) may have a weird behavior here. You could try toArray:
$accounts = Account::where('archive', false)
->select('id', 'display_name')
->get()
->toArray();
Then you could check the result with dd:
dd($accounts);

Awkwardly i found an answer to this immediately after posting it..
Instead of using the following feats of code...
$accounts = Account::where('archive', false)->select('id', 'display_name')->get();
$accounts = (array) $accounts;
I used
foreach($account in $accounts){
$test = new \stdClass();
$test = (array) $test;
$test[$index]['Revenue'] = (double) $account->revenue;
$test[$index]['Expense'] = (double) $account->expense;
$test[$index]['Profit'] = $account->sum;
$test[$index]['ID'] = $id;
$test[$index]['Account Name'] = $display_name;
}
this still is confusing however because ive tried making a new array and then adding the values through that but it wouldnt work..?
EDIT
i fully understand this is a highly ineffecient way of doing things but im working with a deadline and this is working, if you have anything to add please do! ill review the criticism when i have time and hopefully i can improve the code with your help!

Related

Laravel: External variable in callback for chunk

I am trying to implement search in Laravel. I want to search on models.
Since there can be many records in the database, I am trying the chunk function.
public function searchLeads($param)
{
$results = array();
// get all leads
Lead::chunk(100, function($leads) use ($results, $param) {
// search in name
$results = array_merge($results, $this->repository->searchInName($leads, $param));
// search in email
$results = array_merge($results, $this->repository->searchInEmail($leads, $param));
// and so on ...
}
// eliminate duplicates
$collection = collect($results);
$collection = $collection->unique();
$results = $collection->all();
dd($results);
// return $results;
}
Note: The searchIn... functions return array of results and are working as expected.
When I try the above code, I get an empty array. So I changed the following line (added a reference & to $results).
Lead::chunk(100, function($leads) use (&$results, $param) {
Now I get the expected output.
My question is, have I stumbled upon the right solution, or am I missing something that might introduce bugs in the code?
Note:
I know using where clause is a better and efficient way; but I cannot use where for this.
I got the solution after reading a bit about php closures. My real worry was that I am not using the $results array correctly.
But after reading php docs, I know I am doing it correctly.
Please note that I am aware of where clause and it's usage would be much more efficient here. But that's not what I was trying to ask.
to use the search, you could do something like:
$results = Lead::where('mail','like', $param)->orWhere('name','like', $param)->get();
then mysql does the search, which i believe is the fastes way of doing it.
depending on how the search should be done:
...where('mail','like', %$param%)...
https://laravel.com/docs/5.1/queries#where-clauses
else try to describe what the end goal of your search is?

Struggling to understand how this particular code works.

I am faced with a piece of code that does not make a lot of sense to me. I am working on a website using PHP and Smarty template, but there is one line of code regarding arrays that i do not understand how it works.
$SLang = &SLanguage::getInstance();
$q="SELECT * FROM texte where text_lang='{$SLang->lang}' ORDER BY text_id";
$texte = _sqlFetchQuery($q);
foreach($texte as $text)
{
$texteList[$text['text_alias']]['text'] = $text['text_text'];
if($text["text_category"]==3){
$philosophyList[] = $text["text_text"];
$philosophyListSeo[] = $text["text_alias"];
}
}
The output of "var_dump" on $philosophyList gets out only the "text_text" column from the database, and i do now understand the structure of how it gets there. Can someone care to explain? How does this particular line of code works? $texteList[$text['text_alias']]['text'] = $text['text_text'];
It's called a jagged array.
It's shorthand for this:
$texteList[$text['text_alias']] = array('text'=>$text['text_text']);
So it's creating a named array using whatever text is $text['text_alias'] brings out, and assigning as it's value an array with a named "text" element.
But this is irrelevant to $philosophyList[]. To understand how $philosophyList[] is working, you need to understand how foreach works; basically it takes each item in an array (in this case $texte) and assigns the value of that array item to a variable (in this case $text). This is just an easier way to do a for loop. They could just have easily done:
$philosophyList[] = $texte[$i]["text_text"];

PHP adding or subtracting elements from array

I have a query string. For example:
?filters=1,2,3,4
It gets turned into an array:
$filters = explode(',', $_GET['filters']);
You could push a new value on
$filters = array_push($filters, $new->filter);
Then turn it into the query string
http_build_query($filters);
Or, remove a value
$filters = array_diff($filters, [$new->filter]);
Then turn it into the query string
http_build_query($filters);
I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist. Alternative solutions are also welcome.
Thank you.
Hopefully I'm understanding you correctly "I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist.". Also, not sure if it is elegant but may spark other ideas:
$filters = in_array($new->filter, $filters) ?
array_diff($filters, [$new->filter]) :
array_merge($filters, [$new->filter]);
That's about as elegant as it gets, unless you want to use PHP's array notation "hack", e.g.
?filters[]=1&filters[]=2&filters[]=3&etc...
^^---
That'd save you the explode() stage and gives you the ability to treat $_GET['filters'] as an array directly, but at the cost of an uglier/longer URL.
Perhaps you should write 2 functions, "remove" and "add", which would each loop through the array looking for the value in question. Then the remove function could remove it, and the add function could add it. The functions themselves would not be so elegant, but using them would be simple elsewhere in your code.

Javascript variable initialization

There, an odd thing just happened..
Normally I assign my global variables like this:
orders = [];
pOrders = [];
But I was lazy and just wrote:
orders = pOrders = [];
It should mean the same, shouldn't it??
Apparently not because the array pOrder also contained the array orders data. I sat for 15 min looking for a bug in my code but couldn't find any so I just tried writing the variables as I normally would and it worked. Why does this happen?
In PHP, the logic would be the same, but JavaScript seems to behave differently.
Please could anyone provide me with some information, or knowledge..
In the second example, you're explicitly assigning the exact same array instance to two separate variables. There's only one array involved, while in the first case there are two.
I would be somewhat surprised to learn that PHP really would treat those two pieces of code as meaning the same thing.
That code you wrote there last is the same as:
orders = [];
pOrders = orders;
So now you have two variables which are references to the same array. That's why you are exeriencing this behavior.
When instead you do it as you did in your first example:
orders = [];
pOrders = [];
Then you have two completely separate and distinct arrays.
You assigned both variables to refer to the same array instance.
To see what everyone means by "same array instance", run the following JavaScript in your browser:
orders = pOrders = [];
orders.push("hello");
pOrders.push("world");
console.log(orders);
console.log(pOrders);
Check the console output, both messages will say ["hello", "world"].

Reset MySqli pointer?

I'm struggling a bit with resetting a pointer. I want to do this because I'm going to use the same query twice in the same script. As far as I can work out I can do this with resetting the pointer after I've looped trough the fetched array. If there is a better way to do this, I'd love to hear it.
Anyway, this is what I got.
$getEvent = $connection->prepare("SELECT * BLABLA FROM BLABLA");
$getEvent->bind_param("i", $eventID);
$getEvent->execute();
$getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);
while($getEvent->fetch())
{
// Do stuff
}
// Then bunch of code, before finally another
//$getEvent->execute(); //Script doesn't work without this and next line
//$getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);
while($getEvent->fetch())
{
// Do other stuff
}
I've tried with $getEvent->data_seek(0); but no luck. The script only works if I redeclare $getEvent->bind_result. Thanks in advance for any replies.
This places unnecessary extra strain on the database server. Rather than rewind and reuse the result set, store the whole thing in an array to begin with. You may then use it as many times and different ways as you like in the PHP application code.
Update Fixed code so it should work with MySQLi rather than PDO. Also, made the results into an associative array.
$results = array();
while($getEvent->fetch())
{
$results[] = array('eventMember'=>$eventMember, 'eventStaff'=>$eventStaff, 'eventMemberID'=>$eventMemberID, 'eventMemberSuper'=>$eventMemberSuper);
}
// Now use $results however you need to.

Categories