I have array, I want to make selection in it, but before do selection
I want to take 2 numbers in front of each values in array:
$myarray[2] = array(62343,62444,62343,08453,62333);
I want something like this:
$arraysubstr = substr($myarray[2],0,2)
if(($arraysubstr) < 62) //not work (work for first array value)
{
redirect
}else{
no problem
}
I thank all those who want to comment
You can use array_walk() function. It takes two parameters one is array and another is a function. You can perform any operation you want using the function on your array.
function fcn(&$item) {
$item = substr(..do what you want here ...);
}
array_walk($matches, "fcn");
Use array_walk() function to walk through the array. It returns true on success and false on failure. Its accepts two parameters one is array and other is callback fnction.
$myarray[2] = array(62343,62444,62343,08453,62333);
function func($value,$key) {
$item = substr($value,0,2);
if(($item) < 62)
{
echo 'redirect';
}else{
echo 'no problem';
}
}
array_walk($myarray[2], "func");
Related
I'm building a PHP querying a mongodo database. I need to retreive the value of a param from the url, and there is potentially more than one.
An example url would look like this
http://localhost/api/v1/report-01?type=EE&type=ER
How would I retrieve the two values from type.
At the moment I'm only get one, and it's the last one.
if (isset($params["TYPE"]) && in_array($params["TYPE"], ["EE", "ER"])) {
$matchPipeline["TYPE"] = $params["TYPE"];
echo "Printing Variables";
echo $params["TYPE"];
}
The code is only printing ER.
I have no access to the frontend, only the backend so I can't change the URL structure
How would I retrieve the two values from type.
With [ ] after your key
api/v1/report-01?type[]=EE&type[]=ER
You can achieve this by accessing directly to global $_SERVER variable and using preg_match_all, here is an example:
<?php
preg_match_all('/type=(\w+)/', $_SERVER['QUERY_STRING'], $matches);
var_dump($matches[1]);
Just create this function query to array and split the value
function queryToArray($q)
{
$arr = [];
foreach(explode("&", $q) as $l)
{
$b = explode('=', $l);
if ( (is_array($b) && count($b) > 0) )
$arr[$b[0]] = $b[1];
}
return $arr;
}
$arr = parse_url($url_string);
print_r(queryToArray($arr['query']);
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);
}
//*********
I have an array that contains any number of elements, and is allowed to be a multidimensional array, too. My testing example of such array data is:
$arr = array(
array('Material-A', 'Material-B'),
array('Profile-A', 'Profile-B', 'Profile-C'),
array('Thread-A', 'Thread-B'),
// ... any number of elements
);
From this multidimensional array I need to create a single array that is linear in the following format.
$arrFormated = array(
'Material-A',
'Material-A_Profile-A',
'Material-A_Profile-A_Thread-A',
'Material-A_Profile-A_Thread-B',
'Material-A_Profile-A_Thread-C',
'Material-A_Profile-B',
'Material-A_Profile-B_Thread-A',
'Material-A_Profile-B_Thread-B',
'Material-A_Profile-B_Thread-C',
'Material-A_Profile-C',
'Material-A_Profile-C_Thread-A',
'Material-A_Profile-C_Thread-B',
'Material-A_Profile-C_Thread-C',
'Material-B',
'Material-B_Profile-A',
'Material-B_Profile-A_Thread-A'
// Repeat similar pattern found above, etc...
);
For a recursive function, the best that I've been able to come up with thus far is as follows:
private function showAllElements($arr)
{
for($i=0; $i < count($arr); $i++)
{
$element = $arr[$i];
if (gettype($element) == "array") {
$this->showAllElements($element);
} else {
echo $element . "<br />";
}
}
}
However, this code is no where close to producing my desired results. The outcome from the above code is.
Material-A
Material-B
Profile-A
Profile-B
Profile-C
Thread-A
Thread-B
Could somebody please help me with the recursive side of this function so I may get my desired results?
I'd generally recommend thinking about what you want to be recursive. You tried to work with the current element in every recursion step, but your method needs to look at the next array element of the original Array in each recursion step. In this case, it's more useful to pass an index to your recursive function, because the 'current element' (the $arr in showAllElements($arr)) is not helpful.
I think this code should do it:
$exampleArray = array(
array('Material-A', 'Material-B'),
array('Profile-A', 'Profile-B', 'Profile-C'),
array('Thread-A', 'Thread-B','Thread-C'),
// ... any number of elements
);
class StackOverflowQuestion37823464{
public $array;
public function dumpElements($level = 0 /* default parameter: start at first element if no index is given */){
$return=[];
if($level==count($this->array)-1){
$return=$this->array[$level]; /* This is the anchor of the recursion. If the given index is the index of the last array element, no recursion is neccesarry */
}else{
foreach($this->array[$level] as $thislevel) { /* otherwise, every element of the current step will need to be concatenated... */
$return[]=$thislevel;
foreach($this->dumpElements($level+1) as $stringifyIt){ /*...with every string from the next element and following elements*/
$return[]=$thislevel.'_'.$stringifyIt;
}
}
}
return $return;
}
}
$test=new StackOverflowQuestion37823464();
$test->array=$exampleArray;
var_dump($test->dumpElements());
I'm getting this error with my current PHP code:
Notice: TO id was not an integer: 1, 2. 1) APNS::queueMessage ->
How can I convert to an array of strings to an array of integers like in this other question: ID not integer... EasyAPNS ?
I'm basically trying to pass ids (from my database,) to newMessage() like this Apple example:
// SEND MESSAGE TO MORE THAN ONE USER
// $apns->newMessage(array(1,3,4,5,8,15,16));
// ($destination contain a string with the Ids like "1,2,3")
Here is my code below:
if (isset($destination))
{
//$destination = 1,2,..
$dest = explode(",", $destination);
if (isset($time))
{
$apns->newMessage($dest, $time);
}
else
{
$apns->newMessage($dest);
}
$apns->addMessageAlert($message);
$apns->addMessageBadge($badge);
$apns->addMessageSound('bingbong.aiff');
$apns->queueMessage();
header("location:$url/index.php?success=1");
}
I would create a wrapper function that accepts an array, and then call it.
function newMessageArray($array) {
foreach ($array as $element) {
$apns->newMessage($element);
}
}
This way, you can call newMessageArray() with an array of integers, such as array(1,2,3,4,5), and they will all be sent.
Also, you should change the variable names (from $array and $element) to something more meaningful. I don't know what you're trying to do, so I wasn't sure what names to use.
Your Question is not clear, It's only a guess work.
It seems to be error in convert integer, try
$dest = explode(",", $destination);
$destArray = array();
foreach($dest as $key => $val) {
$destArray[$key] = intval($val);
}
if (isset($time))
{
$apns->newMessage($destArray, $time);
}
else
{
$apns->newMessage($destArray);
}
Convert where the string is not integer using 'intval'.
I believe what you may be looking for is how to do this:
You have ids in your database table, right? And you are trying to get multiple ids into an array so that the array can be used in $apns->newMessage() call, right? (I checked the source for this...) But, the ids are somehow coming over as strings instead of ints.
So, you probably want to just make sure that the new array is made up of ints, like this:
function to_int($x) {
return (int)$x;
}
$dest = array_map("to_int", $dest);
There are probably other ways to do this, but this way, you at least know that you have int variables in that array. Hope that helps!
Ok. I've written a simple(ish) function to take an argument and return the same argument with the danger html characters replaced with their character entities.
The function can take as an argument either a string, an array or a 2D array - 3d arrays or more are not supported.
The function is as follows:
public function html_safe($input)
{
if(is_array($input)) //array was passed
{
$escaped_array = array();
foreach($input as $in)
{
if(is_array($in)) //another array inside the initial array found
{
$inner_array = array();
foreach($in as $i)
{
$inner_array[] = htmlspecialchars($i);
}
$escaped_array[] = $inner_array;
}
else
$escaped_array[] = htmlspecialchars($in);
}
return $escaped_array;
}
else // string
return htmlspecialchars($input);
}
This function does work, but the problem is that I need to maintain the array keys of the original array.
The purpose of this function was to make it so we could literally pass a result set from a database query and get back all the values with the HTML characters made safe. Obviously therefore, the keys in the array will be the names of database fields and my function at the moment is replacing these with numeric values.
So yeah, I need to get back the same argument passed to the function with array keys still intact (if an array was passed).
Hope that makes sense, suggestions appreciated.
You can use recursion rather than nesting loads of foreaches:
function html_safe($input) {
if (is_array($input)) {
return array_map('html_safe', $input);
} else {
return htmlspecialchars($input);
}
}
Ok I think I've figured this one out myself...
my foreach loops didn't have any keys specified for example they were:
foreach($array_val as $val)
instead of:
foreach($array_val as $key => $val)
in which case I could have preserved array keys in the output arrrays.