PHP array merge: is not an array? - php

I'm tryin to merge an array that I have when it is being created through a function
I have a function, and it returns an array.
class myarray
{
public function getAr($id)
{
// mysql query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
public function get3($id)
{
// mysl query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
}
How come I tried to merge together the array:
$get = new myarray();
while($row = $fet->fetch(PDO::FETCH_ASSOC))
{
$arrayAr = $get->getAr($id);
$array3 = $get->get3($id);
$new_array = array_merge($arrayAr ,$array3); //this gives me the error
print_r($arrayAr); //displays array
}
print_r($arrayAr); //displays nothing, why is that?
It says that its not an array?
array_merge() [function.array-merge]: Argument #1 is not an array
But I can print_r($arrayAr); and its like an array inside the while loop, but it doesn't display anything outside of it?
when I tried this...
$new_array = array_merge((array)$arrayAr ,(array)$array3);
It doesn't display an error, but it isn't merged either.
Help?
Thanks

You $arrayAr is local variable and 2nd print_r() is used beyond of scope of his variable. If you need it available wider, "declare" it before foreach, with i.e. $arrayAr = array(); (or whatever value you want - it is not important in this case, yet array() makes code clear).

Related

Why does this way of adding values to an array in php work?

I use something like
$data = [];
foreach (){
$data[] = $api_content;
}
return $data;
the $data array does not get overwritten. Instead the values of $api_content get appended.
Is that right??? Why? I thought it gets overwritten....

store multiple values in associative array and return that array in php

I have seen a lot of answers (so please don't mark it duplicate) to store values in associative array but I want to return that array in PHP. Here is my code. It prints all values but only return the first value. I want the whole array returned to use in another function.
Please help
function xml_parsing($response,$size,$array)
{
for($k=0;$k<$size;$k++)
{
$price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice->FormattedPrice;
$myarray[$k]=explode(',',$array["ItemId"]);
$update_fields=array('sku','price');
if($price=='')
{
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
}
else
{
$price_trimed=ltrim($price,'$');
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
// I store the values here using a loop
}
}
print_r($Col_array);
return $col_array; //but here it return only first value
// But I want to return the whole array**
// I can't return it inside loop because it terminates
// the loop and the function
}
Some pseudocode:
//first, initialize empty array:
$Col_array = [];
//do the loop thing.
while(...){
//inside the loop:
//add to array:
$Col_array []= array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
}//loop ends here
print_r($Col_array); //<----- all values.
return $Col_array;
notice how one uses []= to append to an array.
Actually, the mistake here is you are not storing the data that is traversed in the loop. You need to push $Col_array to the main array to get the desired outcome. Here is your code
function xml_parsing($response,$size,$array)
{
//create an empty array before entering the for loop.
$main_array = array();
for($k=0;$k<$size;$k++)
{
$price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice->FormattedPrice;
$myarray[$k]=explode(',',$array["ItemId"]);
$update_fields=array('sku','price');
if($price=='')
{
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
}
else
{
$price_trimed=ltrim($price,'$');
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
// I store the values here using a loop
}
//Here you push the $col_array to main_array
array_push($main_array,$Col_array);
//This will store whole bunch of data as multi dimensional array which you can use it anywhere.
}
print_r($main_array);
return $main_array;
}
I think you will get what you desired.
Here I want to answer my own question
function xml_parsing($response,$size,$array)
{
for($k=0;$k<$size;$k++)
{
$price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice-
>FormattedPrice;
//echo "PKkkkkkkkk".$array["ItemId"]."llllll";
$myarray[$k]=explode(',',$array["ItemId"]);
//print_r($myarray[$k]);
$update_fields=array('sku','price');
if($price=='')
{
// $Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
/*Here is the solution we have to index it inside the loop like a 2D
array now it contain an array inside which array of key value pair is
present (associative array) which i wanted */
//**********
$Col_array[$k]['sku']=$myarray[$k][$k];
$Col_array[$k]['price']="-1";
//*********
}
else
{
$price_trimed=ltrim($price,'$');
// final array to be stored in database
// $Col_array=array('sku'=>"".$myarray[$k]
[$k]."",'price'=>$price_trimed);
$Col_array[$k]['sku']=$myarray[$k][$k];
$Col_array[$k]['price']=$price_trimed;
}
}
return $Col_array;
}
//*******
//To Print the returned array use
foreach ($Col_array as $value) {
print_r($value);
}
//*********

Function returns "Array" instead of actual output

I have this code:
function returnArray() {
$intData = array("1", "3");
return $intData[array_rand($intData)];
}
I'm trying to make a function similar to the one above.
Instead of adding integers with commas I'm trying to implode the commas with the integers.
Sort of like a dynamic version of the above using json_decode, file_get_contents, a foreach loop, array, array_rand & return
This is my code:
function Something() {
foreach (json_decode(file_get_contents('removed'), true) as $jsonArr) {
$arrData = array(implode(",", $jsonArr));
$roundData = $arrData[array_rand($arrData)];
return $roundData;
}
}
I was just wondering if I'm doing it right and if the array is correct or not.
Also it doesn't return anything from the array.
When I try to implode, it throws an error
implode invalid argument
It seems you're trying to print a random room_id from the JSON response.
The problem lies here:
$intData = array(implode(",", $arrRoomsReverse['room_id']));
You can't initialize an array like that.
Just push the room_id element to the array, like so:
$intData[] = $arrRoomsReverse['room_id'];
Now, you can simply get a random room_id outside the loop:
$intRoom = $intData[array_rand($intData)];
The function would look like:
function returnArray()
{
$str = file_get_contents('...');
$jsonArr = json_decode($str, true);
foreach ($jsonArr as $arrRoomsReverse)
{
$intData[] = $arrRoomsReverse['room_id'];
}
$intRoom = $intData[array_rand($intData)];
return $intRoom;
}
And to call the function:
echo returnArray();

Passing and returnging array to the functions

I have created two arrays. I wanna pass these two array to any function. I am beginner with function so tried with rough code to achieve my task. As I have some values in $cntctnum and $cntcttype named array.
$cntctnum = array();
$cntcttype = array();
$response = array();
function play_with_array($cntctnum, $cntcttype){
$contactnumber= $cntctnum[];
$cntcttype = $cntcttype[];
// some code to play with array.
return resultarray();
}
$response = play_with_array($cntctnum, $cntcttype);
Is this right way to pass function in array?
Is I need to declare $response as array before or when I return resultarray(), it will automatically consider it as array?
You don't need to define $response as array beforehand, but it might be a good idea to do so anyway depending on what the code afterwards expects.
In your function you don't return a function call resultarray() but a new array:
function play_with_array($cntctnum, $cntcttype) {
$contactNumber = $cntctnum; // You don't need the assignment! Note: No brackets here!
$resultArray = array();
// Do something here
return $resultArray;
}
You have:
$cntctnum = array();
$cntcttype = array();
$response = array();
function play_with_array($cntctnum, $cntcttype){
$contactnumber= $cntctnum[]; // don't need []
$cntcttype = $cntcttype[]; // don't need []
// some code to play with array.
return resultarray(); // this is a function?
}
$response = play_with_array($cntctnum, $cntcttype);
I would do something like this
$cntctnum = array();
$cntcttype = array();
function play_with_array($contactnumber, $cntcttype){
// some code to play with array.
$response = array($contactnumber,$cntcttype);
return $response;
}
$response = play_with_array($cntctnum, $cntcttype);
echo "<pre>".print_r($response,true)."</pre>";
Rahul, you pass array to a function just like you pass any other variable to a function. The reason to have a function is to have a block of code that can be re-used to perform the same set of calculations, etc.
It's hard to understand what you're trying to do inside your function. If this is something that's repeatable, meaning: compare array 1 vs array 2, get the bigger one, and return some sort of variation of that, then YES, create a function. If you have some code inside your function that is very specific to this page only and to these 2 arrays, you don't need the function. Just write the code inline.
Is I need to declare $response as array before or when I return resultarray(), it will automatically consider it as array?
No, you don't. If you resultarray variable inside a function is truly an array, you're good to go.

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