Laravel make array of another array objects - php

I have general data array and I need to get array of specific data inside this general array so I can match it against my database.
Code
$nums = [];
foreach($request->phones as $phone) {
foreach($phone['_objectInstance']['phoneNumbers'] as $number) {
$nums = $number['value'];
}
}
$contacts = User::whereIn('phone', $nums)->get();
PS: $number['value'] is the data that I want to make array of it.
Sample data that I receive in backend
current error
Argument 1 passed to Illuminate\\Database\\Query\\Builder::cleanBindings() must be of the type array, string given, called in /home/....../vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php on line 918
exception: "TypeError"
Question
How can I make array of my numbers?
Ps: please if you know cleaner way to write this code, than my code above don't hesitate to share with me.

You're assigning $nums to be a new string on every iteration of the loop, rather than appending it to the array.
Just switch this line out:
$nums = $number['value'];
For
$nums[] = $number['value'];
Here are the docs for array_push(), which is the long way of writing the second line.

You are declaring $nums array, but inside the loop, you re-declaring it by a string again.
Fix the array assignments like that.
$nums[] = $number['value'];

Related

Foreach loop over array of objects Laravel

I'm receiving this array of objects and need to iterate over it, but the problem is that I need to get the value of the next item when its iterating, to compare the value of the current object with the next one, and if it's a different value, split this array in two.
So, I was doing it with next() php function:
//looking for the next register in the array
$next = next($finances);
//first array if exist different values
$aiuaEd = [];
//second array if exist different values
$aiua = [];
foreach ($finances as $finance) {
if ($finance->cnpj <> $next->cnpj) {
$aiua[] = $finance;
} else {
$aiuaEd[] = $finance;
}
}
This code works fine at some point, but then I got this error:
Trying to get property 'cnpj' of non-object in
I don't know why sometimes works well and sometimes don't, debugging this variables, I found that if my array have 2 objects inside only, when I'm looping over it, the $next->cnpj variable came as empty, and sometimes don't.
Can someone help me with this?
I solved it with a different approach, instead of using php next(), I first loop over this array saving the cnpj's into an array.
$cnpjs = [];
foreach($finances as $finance){
$cnpj[] = $finance->cnpj;
}
Then I use array_unique() to group this 2 differents CNPJ's and sort() to get the correct keys order.
//grouping cnpjs as unique, should exist only 2 keys
$cnpj = array_unique($cnpj);
//sort array keys to get in order
sort($cnpj);
Then I iterate over my $finances array again, but now I'm counting if this $cnpj array has more than 2 positions, which means that I have to split this data in two differents arrays.
foreach($finances as $finance){
if(count($cnpj) > 1){
if($finance->cnpj == $cnpj[1]){
$aiua[] = $finance;
}else{
$aiuaEd[] = $finance;
}
}else{
$aiuaEd[] = $finance;
}
}
I'm pretty sure that this is not the best approach for that problem, or at least the most optimized one, so I'm open for new approach's suggestions!
Just posting how I solved my problem in case anyone having the same one.
Notice that this approach is only usable because I know that will not exist more than 2 different's CNPJ's in the array.

Pushing an element in multidimensional array in PHP

so I am working with a multidimensional array.
For example, the output data I am trying to get is like this:
[[element 1],[element 2], [element 3]]
This is my PHP code (minus the entire prepared statement which goes above the bind ((not included as this is working fine)):
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_fcm_old, $vessel_hull_id_new, $vessel_hull_id_old, $vessel_name_new, $vessel_name_old, $vessel_length_new, $vessel_length_old, $vessel_manufacturer_new, $vessel_manufacturer_old, $vessel_manufacturer_id_new, $vessel_manufacturer_id_old, $vessel_year_new, $vessel_year_old, $vessel_value_new, $vessel_value_old, $owner_id_new, $owner_id_old, $loss_payee_id_new, $loss_payee_id_old, $policy_id_new, $policy_id_old, $policy_start_date_new, $policy_start_date_old, $policy_end_date_new, $policy_end_date_old, $vessel_fcm, $vessel_hull_id, $vessel_name, $vessel_manufacturer_id);
while ($insertquery->fetch()){
if($vessel_fcm_new != $vessel_fcm_old){
$data = array($vessel_fcm_new, $vessel_fcm_old);
}
if ($vessel_name_new != $vessel_name_old){
array_push($data, $vessel_name_new, $vessel_name_old);
}
$data_return[] = $data;
}
echo json_encode($data_return);
Basically, the code is initiated to iterate through each database row, and if the condition is met it will build an array, and add the array to the array object. So the outcome would look like this, if the matching conditions are met:
[[row 1], [row2], [row3]]
However, I am getting this error:
Warning: array_push() expects parameter 1 to be array, null given in C:\htdocs\alterajax.php on line 16
But I am specifying the array already, or at least I think I am ($data).
This is also what I see as the output:
[null,null,null,null,null,["FCMjgis","fFH465","Smokey","GIIGE"]]
I'm sure this is just something minor, but I would appreciate some guidance if you can assist. Thank you in advance!
Like I said, just initialize your variable or test if its initialized using isset
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_fcm_old, $vessel_hull_id_new, $vessel_hull_id_old, $vessel_name_new, $vessel_name_old, $vessel_length_new, $vessel_length_old, $vessel_manufacturer_new, $vessel_manufacturer_old, $vessel_manufacturer_id_new, $vessel_manufacturer_id_old, $vessel_year_new, $vessel_year_old, $vessel_value_new, $vessel_value_old, $owner_id_new, $owner_id_old, $loss_payee_id_new, $loss_payee_id_old, $policy_id_new, $policy_id_old, $policy_start_date_new, $policy_start_date_old, $policy_end_date_new, $policy_end_date_old, $vessel_fcm, $vessel_hull_id, $vessel_name, $vessel_manufacturer_id);
while ($insertquery->fetch()){
if($vessel_fcm_new != $vessel_fcm_old){
$data = array($vessel_fcm_new, $vessel_fcm_old);
}
if (isset($data) && $vessel_name_new != $vessel_name_old){
array_push($data, $vessel_name_new, $vessel_name_old);
$data_return[] = $data;
}
}
echo json_encode($data_return);
Make sure to initialize your variables!
In this case, all I needed to do was initialize the $data array. I did this by placing $data = []; (or also $data = array();) on the line above the while loop

Text file data to an associative array in PHP and search data

I'm a beginner in PHP. I have a text file like this:
Name-Id-Number
Abid-01-80
Sakib-02-76
I can take the data as an array but unable to take it as an associative array. I want to do the following things:
Take the data as an associative array in PHP.
Search Number using ID.
Find out the total of Numbers
I believe I understand what you want, and it's fairly simple. First you need to read the file into a php array. That can be done with something like this:
$filedata = file($filename, FILE_IGNORE_NEW_LINES);
Now build your desired array using a foreach() loop, explode and standard array assignment. Your search requirement is unclear, but in this example, I make the associated array element into an array that is also an associative array with keys for 'id' and 'num'.
As you create the new array, you can compute your sum, as demonstrated.
<?php
$filedata = array('Abid-01-80', 'Sakib-02-76');
$lineArray = array();
$numTotal = 0;
foreach ($filedata as $line) {
$values = explode('-', $line);
$numTotal += $values[2];
$lineArray[$values[0]] = array('id' => $values[1], 'num' => $values[2]);
}
echo "Total: $numTotal\n\n";
var_dump($lineArray);
You can see this code demonstrated here
Updated response:
Keep in mind that notices are not errors. They are notifiying you that your code could be cleaner, but are typically suppressed in production.
The undefined variable notices are coming because you are using:
$var += $var without having initialized $var previously. Note that you were inconsistent in this practice. For example you initialized $numTotal, so you didn't get a notice when you used the same approach to increment it.
Simply add just below $numTotal = 0:
$count = 0;
$countEighty = 0;
Your other notices are occurring most likely due to a blank line or string in your input that does not follow the pattern expected. When explode is executed it is not returning an array with 3 elements, so when you try and reference $values = explode('-', $line); you need to make sure that $line is not an empty string before you process it. You could also add a sanity check like:
enter code hereif (count($values) === 3) { // It's ok to process

Difference between array_push() and $array[] =

In the PHP manual, (array_push) says..
If you use array_push() to add one element to the array it's better to
use $array[] = because in that way there is no overhead of calling a
function.
For example :
$arr = array();
array_push($arr, "stackoverflow");
print_r($arr);
vs
$arr[] = "stackoverflow";
print_r($arr);
I don't understand why there is a big difference.
When you call a function in PHP (such as array_push()), there are overheads to the call, as PHP has to look up the function reference, find its position in memory and execute whatever code it defines.
Using $arr[] = 'some value'; does not require a function call, and implements the addition straight into the data structure. Thus, when adding a lot of data it is a lot quicker and resource-efficient to use $arr[].
You can add more than 1 element in one shot to array using array_push,
e.g. array_push($array_name, $element1, $element2,...)
Where $element1, $element2,... are elements to be added to array.
But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.
The difference is in the line below to "because in that way there is no overhead of calling a function."
array_push() will raise a warning if the first argument is not
an array. This differs from the $var[] behaviour where a new array is
created.
You should always use $array[] if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.
array_push — Push one or more elements onto the end of array
Take note of the words "one or more elements onto the end"
to do that using $arr[] you would have to get the max size of the array
explain:
1.the first one declare the variable in array.
2.the second array_push method is used to push the string in the array variable.
3.finally it will print the result.
4.the second method is directly store the string in the array.
5.the data is printed in the array values in using print_r method.
this two are same
both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element
Thought I'd add to the discussion since I believe there exists a crucial difference between the two when working with indexed arrays that people should be aware of.
Say you are dynamically creating a multi-dimensional associative array by looping through some data sets.
$foo = []
foreach ($fooData as $fooKey => $fooValue) {
foreach ($fooValue ?? [] as $barKey => $barValue) {
// Approach 1: results in Error 500
array_push($foo[$fooKey], $barKey); // Error 500: Argument #1 ($array) must be of type array
// NOTE: ($foo[$fooKey] ?? []) argument won't work since only variables can be passed by reference
// Approach 2: fix problem by instantiating array beforehand if it didn't exist
$foo[$fooKey] ??= [];
array_push($foo[$fooKey], $barKey);
// Approach 3: One liner approach
$foo[$fooKey][] = $barKey; // Instantiates array if it doesn't exist
}
}
Without having $foo[$fooKey] instantiated as an array beforehand, we won't be able to do array_push without getting the Error 500. The shorthand $foo[$fooKey][] does the heavy work for us, checking if the provided element is an array, and if it isn't, it creates it and pushes the item in for us.
I know this is an old answer but it might be helpful for others to know that another difference between the two is that if you have to add more than 2/3 values per loop to an array it's faster to use:
for($i = 0; $i < 10; $i++){
array_push($arr, $i, $i*2, $i*3, $i*4, ...)
}
instead of:
for($i = 0; $i < 10; $i++){
$arr[] = $i;
$arr[] = $i*2;
$arr[] = $i*3;
$arr[] = $i*4;
...
}
edit- Forgot to close the bracket for the for conditional
No one said, but array_push only pushes a element to the END OF THE ARRAY, where $array[index] can insert a value at any given index. Big difference.

PHP arrays. inserting "$key" => "$value" pair into array with array_push();

Why won't this work?
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$key = $slidetotal;
array_push($slideids[$key], $rowcs['id']);
$slidetotal++;
}
I get this error:
[phpBB Debug] PHP Notice: in file ///*.php on line 161: array_push() [function.array-push]: First argument should be an array
Although someone has commented you can do this on this page:
http://php.net/manual/en/function.array-push.php , (find: "to insert a "$key" => "$value" pair into an array")
What is the next best way to insert a list of single values into a php array? By the way, I really can't believe it's hard to find something on this with google.com. Seriously?
That PHP.net comment is incorrect. That is pushing $rowcs['id'] onto the array $slideids[$key], not the array $slideids.
You should be doing the following, in place of your array_push() call:
$slideids[$key] = $rowcs['id'];
Why don't you do;
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[$slidetotal] = $rowcs['id'];
$slidetotal++;
}
Also you can do like below if you don't need the key to start from 1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[] = $rowcs['id'];
}
ummm hard-searching will work for google I think :)
anyway, error tells you everything you need to know. that means first argument of array_push is not an array, you give a single value (string) to array_push ($slideids[$key]).
Also why do you need to use array_push in php? I'd rather use
$slideids[] = $rowcs['id'];
and what you're trying to do is:
$slideids[$key] = $rowcs['id'];
i guess...

Categories