Pushing an element in multidimensional array in PHP - 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

Related

Laravel make array of another array objects

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'];

PHP extract key-value in array json and restructure

Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.

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...

A $_GET input parameter that is an Array

I'm trying to pass 3 parameter to a script, where the 3rd parameter $_GET['value3'] is supposed to be an array
$_GET['value1']
$_GET['value2']
$_GET['value3'] //an array of items
I'm calling the script like this: (notice my syntax for value3, I'm not sure it's correct)
http://localhost/test.php?value1=test1&value2=test2&value3=[the, array, values]
I then use a foreach to hopefully loop through the third parameter value3 which is the array
//process the first input $_GET['value1']
//process the second input $_GET['value2']
//process the third input $_GET['value3'] which is the array
foreach($_GET['value3'] as $arrayitem){
echo $arrayitem;
}
but I get the error Invalid argument supplied for foreach()
I'm not sure if my methodology is correct. Can some clarify how you'd go about doing the sort of thing
There is no such thing as "passing an array as a URL parameter" (or a form value, for that matter, because this is the same thing). These are strings, and anything that happens to them beyond that is magic that has been built into your application server, and therefore it is non-portable.
PHP happens to support the &value3[]=the&value3[]=array&value3[]=values notation to automagically create $_GET['value3'] as an array for you, but this is special to PHP and does not necessarily work elsewhere.
You can also be straight-forward and go for a cleaner URL, like this: value3=the,array,values, and then use explode(',', $_GET['value3']) in your PHP script to create an array. Of course this implies that your separator char cannot be part of the value.
To unambiguously transport structured data over HTTP, use a format that has been made for the purpose (namely: JSON) and then use json_decode() on the PHP side.
try
http://localhost/test.php?value1=test1&value2=test2&value3[]=the&value3[]=array&value3[]=values
For arrays you need to pass the query parameters as
value3[]=abc&value3[]=pqr&value3[]=xyz
You can cast the name of the index in the string too
?value1[a]=test1a&value1[b]=test1b&value2[c][]=test3a&value2[c][]=test3b
would be
$_GET['value1']['a'] = test1a
$_GET['value1']['b'] = test1b
$_GET['value2']['c'] = array( 'test3a', 'test3b' );
http://php.net/manual/en/reserved.variables.get.php
Check out the above link..
You will see how the GET method is implemented.
What happens is that the URL is taken, it is delimited using '&' and then they are added as a key-value pair.
public function fixGet($args) {
if(count($_GET) > 0) {
if(!empty($args)) {
$lastkey = "";
$pairs = explode("&",$args);
foreach($pairs as $pair) {
if(strpos($pair,":") !== false) {
list($key,$value) = explode(":",$pair);
unset($_GET[$key]);
$lastkey = "&$key$value";
} elseif(strpos($pair,"=") === false)
unset($_GET[$pair]);
else {
list($key, $value) = explode("=",$pair);
$_GET[$key] = $value;
}
}
}
return "?".((count($_GET) > 0)?http_build_query($_GET).$lastkey:"");
}
Since, they are added as a key-value pair you can't pass array's in the GET method...
The following would also work:
http://localhost/test.php?value3[]=the&value3[]=array&value3[]=values
A more advanced approach would be to serialize the PHP array and print it in your link:
http://localhost/test.php?value3=a:3:{i:0;s:3:"the";i:1;s:5:"array";i:2;s:6:"values";}
would, essentially, also work.

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories