Function returns "Array" instead of actual output - php

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();

Related

Removing array index reference when using json_encode()

I have made a small application using jQuery's datepicker. I am setting unavailable dates to it from a JSON file which looks like this:
{ "dates": ["2013-12-11", "2013-12-10", "2013-12-07", "2013-12-04"] }
I would like to check if a date given is already in this list and remove it if so. My current code looks like this:
if (isset($_GET['date'])) //the date given
{
if ($_GET['roomType'] == 2)
{
$myFile = "bookedDates2.json";
$date = $_GET['date'];
if (file_exists($myFile))
{
$arr = json_decode(file_get_contents($myFile), true);
if (!in_array($date, $arr['dates']))
{
$arr['dates'][] = $_GET['date']; //adds the date into the file if it is not there already
}
else
{
foreach ($arr['dates'] as $key => $value)
{
if (in_array($date, $arr['dates']))
{
unset($arr['dates'][$key]);
array_values($arr['dates']);
}
}
}
}
$arr = json_encode($arr);
file_put_contents($myFile, $arr);
}
}
My problem here is that after I encode the array again, it looks like this:
{ "dates": ["1":"2013-12-11", "2":"2013-12-10", "3":"2013-12-07", "4":"2013-12-04"] }
Is there a way to find the date match in the JSON file and remove it, without the keys appearing after the encode?
Use array_values() for your issue:
$arr['dates'] = array_values($arr['dates']);
//..
$arr = json_encode($arr);
Why? Because you're unsetting array's key without re-ordering it. So after this the only way to keep that in JSON will be encode keys too. After applying array_values(), however, you'll get ordered keys (starting from 0) which can be encoded properly without including keys.
You are ignoring the return value of array_values in your existing attempt to reindex the array. Correct is
$arr['dates'] = array_values($arr['dates']);
The reindexing should also be moved outside the foreach loop, there is no point in reindexing multiple times.
In Laravel collections(just in case) you can do
$newArray = $collection->values()->toArray();
or
$jsonEncoded = $collection->values()->toJson();
Just pass second parameter as 'JSON_PRETTY_PRINT' to json_encode() function:
json_encode($arr, JSON_PRETTY_PRINT);
or
json_encode($arr, 128);

PHP array merge: is not an array?

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

Sending array as one variable from JavaScript to PHP

I have a form, and the URL is like this:
http://hostname/projectname/classname/methodname/variablename
And in my JavaScript, I fill an array like this:
var currentrelations = new Array();
$(".ioAddRelation").each(function(index) {
currentrelations[index] = $(this).html();
});
And this array has two values ['eeeeee','eeeeee']
So the url is:
http://localhost/Mar7ba/InformationObject/addIO/eeeeee,eeeeee
And in my PHP, in the class InformationObject, on the method addIO:
public function addIO($currentRelations =null) {
$name = $_POST['name'];
$type = $_POST['type'];
$concept = $_POST['concept'];
$contents = $_POST['contents'];
$this->model->addIO($name, $type, $concept, $contents);
if (isset($_POST['otherIOs'])) {
$otherIOs = $_POST['otherIOs'];
$this->model->addOtherIOs($name, $otherIOs);
}
$NumArguments = func_num_args();
if ($currentRelations!=null) {
$IOs = $_POST['concetedIOs'];
$this->model->setIoRelations($name,$IOs, $currentRelations);
}
exit;
include_once 'Successful.php';
$s = new Successful();
$s->index("you add the io good");
}
But when I print the array $currentRelations using this statement:
echo count($currentRelations)
The results was 1 not 2, and when I print the first element using thie statement echo $currentRelations[0] I get e not eeeeee
why is that? What is the solution? What am I doing wrong?
As I commented, the $currentRalations is a string, so using count on any type which is not an array or an object will return 1.
Also, note that when you do this $currentRelations[0] on a string, you are accessing a character in the zero-based index of the string. As strings are arrays of characters you can use the square array brackets to access specific chars within strings. This is why echo $currentRelations[0]; printed e in your code.
To split a string you should use the explode function like this:
$curRel = explode(',', $currentRelations);
and then see what you get
var_dump($curRel);
Hope it helps.

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