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

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

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

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

foreach () Error

I'm getting the following warning when running this script:
Warning: Invalid argument supplied for foreach()
This is the script:
$values = array();
foreach ($_POST['rights'] as $right_id)
{
$values[] = '(' . $id . ', ' . $right_id . ')';
}
$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.
The strange part is that on a different page with the same kind of input it gives no errors.
The question: What is wrong with it?
check $_POST['rights']
var_dump($_POST['rights']);
I think $_POST['rights'] is not an array.
foreach must take an array, you're passing it an integer. You can't iterate over an integer.
A wise move might be to check whatever you're about to iterate over is indeed an array:
if(is_array($_POST['rights'])){
foreach($_POST['rights'] as $value){
//Whatever you want to do with each $value
}
}
else {
//Let the user know it's hit the fan…
throw new Exception('Help, I\'m not an array :(')
}
PHP docs for arrays: http://php.net/manual/en/language.types.array.php
PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php
As per your statement $_POST['rights'] is not an array.
It is probably a simple string having 1,2,3,4
You need to convert it into an array with explode function.
e.g
$_POST['rights'] = explode(",", $_POST['rights']);
Then your for loop will work.
The passed array $_POST['rights'] probably is empty.
EDIT:
Like Mark Baker said an empty array is fine. You should go with the other answers.

creating key=>value pairs with foreach loops

here's my issue:
I have a program in the command line that has access to tens of thousands of users. The idea is that you want to be able to get all the information about a user by simply inputting their username. So, because I want to work in php, I've done the following
$user_info = array();
exec('uwdir -v userid=nvidovic', $user_info);
To give you an oversimplified version of what a var_dump on $user_info would look like, it would be something like this:
array(2){
[0] => "first: N"
[1] => "last: Vidovic"
}
I'd like to be able to do this $user[first] => N
This is what I've come up with (not for the real data from command line):
$full_name = array("first: N", "last: Vidovic");
var_dump($full_name);
foreach ($full_name as $part_name) {
$exploded = explode(":", $part_name);
$make_array = array($exploded[0] => $exploded[1]);
echo $make_array["first"];
}
Clearly, this doesn't work. But my question is why? Does anyone know how I can do what I explained above?
I'm really, really, really...really stuck
THANKS to anyone in advance!!
EDIT:
Great answers, thank you. One last thing though, I keep getting the error messages Notice: Undefined offset: 1 and Notice: Undefined offset: 0 for the code below:
$user_info = array();
exec('uwdir -v userid=nvidovic', $user_info);
foreach ($user_info as $info) {
$exploded_info = explode(":", $info);
$info_array[$exploded_info[0]] = $exploded_info[1];
}
echo $info_array["displayName"];
Anyone know why this is happening? I thought the explode function would break up the single string into an array of two strings, right?
Instead of
$make_array = array($exploded[0] => $exploded[1]);
try
$make_array[$exploded[0]] = $exploded[1];
Make sure you put $make_array = array(); before this line, just to make sure it's an empty array.
$full_name = array("first: N", "last: Vidovic");
//var_dump($full_name);
foreach ($full_name as $part_name) {
$exploded = explode(":", $part_name);
$make_array[$exploded[0]] = $exploded[1];
// echo $make_array["first"];
}
print_r($make_array);
http://codepad.org/JvcPdBeq
Because the line
$make_array = array($exploded[0] => $exploded[1]);
overwrites the contents of the whole array. So on the last step you will have only one element there.

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