in_array function not working right - php

I am using a multidimensional array to hold the variables for a given page. I am trying to get a string from the url and match it with an array within my template array to pull the correct variables to display on the page.
Here is my array:
$template = array(
"index" => array(
"title" => "Dashboard",
"model" => "model/dash.php"
),
"input" => array(
"title" => "Dashboard",
"model" => "model/input.php"
),
"jobboard" => array(
"title" => "Job Board",
"model" => "model/job_board.php"
),
"jobcreate" => array(
"title" => "Job Creator",
"model" => "model/job_create.php"
)
);
And here is what I am using to try and verify the pages:
if(isset($_GET['page'])){ $page = $_GET['page']; }
if(in_array($page, $template)){
$title = $template[$page]['title'];
$model = $template[$page]['model'];
echo "yes";
}else{
$title = $template['index']['title'];
$model = $template['index']['model'];
echo "no";
}
The echo "yes/no"; is what I am using to debug if it is working or not but no matter what I have done it just keeps on outputting no.

Take a look at the documentation of php's in_array()
in_array — Checks if a value exists in an array
It looks like your intention is to check against the index of the array, rather than the value. The values in the array are arrays.
Try using array_key_exists() instead.
if (array_key_exists($page, $template)) {
$title = $template[$page]['title'];
$model = $template[$page]['model'];
echo "yes";
}
else {
$title = $template['index']['title'];
$model = $template['index']['model'];
echo "no";
}

in_array() looks at values. It is probably keys you're after.
You can check that with array_key_exists().

Related

extract json objects from an array in php [duplicate]

From PHP code I want to create an json array:
[
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"}
]
How can I do this?
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
...
etc.
After that.
json_encode($associativeArray);
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
That's how I am able to do with the help of solution given by #tdammers below.
The following line will be placed inside foreach loop.
$array[] = array('power' => trim("Some value"), 'time' => "time here" );
And then encode the array with json encode function
json_encode(array('newvalue'=> $array), 200)
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.
<?php
// define a JSON Object class
class jsonOBJ {
private $_arr;
private $_arrName;
function __construct($arrName){
$this->_arrName = $arrName;
$this->_arr[$this->_arrName] = array();
}
function toArray(){return $this->_arr;}
function toString(){return json_encode($this->_arr);}
function push($newObjectElement){
$this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
}
function add($key,$val){
$this->_arr[$this->_arrName][] = array($key=>$val);
}
}
// create an instance of the object
$jsonObj = new jsonOBJ("locations");
// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));
$jsonObj->add("location","TestLoc3"); // from key:val pairs
echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>
Will output:
Array
(
[locations] => Array
(
[0] => Array
(
[location] => TestLoc1
)
[1] => Array
(
[location] => TestLoc2
)
[2] => Array
(
[location] => TestLoc3
)
)
)
{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}
To iterate, convert to a normal object:
$myObj = $jsonObj->toArray();
Then:
foreach($myObj["locations"] as $locationObj){
echo $locationObj["location"] ."<br />";
}
Outputs:
TestLoc1 TestLoc2 TestLoc3
Access direct:
$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];
A practical example:
// return a JSON Object (jsonOBJ) from the rows
function ParseRowsAsJSONObject($arrName, $rowRS){
$jsonArr = new jsonOBJ($arrName); // name of the json array
$rows = mysqli_num_rows($rowRS);
if($rows > 0){
while($rows > 0){
$rd = mysqli_fetch_assoc($rowRS);
$jsonArr->push($rd);
$rows--;
}
mysqli_free_result($rowRS);
}
return $jsonArr->toArray();
}

http_build_query giving me get parameters of the same name [duplicate]

This question already has an answer here:
Build query string with indexed array data
(1 answer)
Closed 7 months ago.
I'm sending multiple parameters to another page, and I am using http_build_query() to do this. The following code:
$array = array();
if(!empty($_POST['modelcheck'])){
foreach($_POST['modelcheck'] as $selected){
$array[] = $selected;
}
}
$args = array
(
'pricefrom' => $fromval,
'priceto' => $toval,
'model' => $array
);
$params = http_build_query($args);
$cleanedParams = preg_replace('/%5B(\d+?)%5D/', '', $params);
header("Location: ../page2.php?" . $cleanedParams);
gives me a url:
page2.php?pricefrom=10000&priceto=60000&model=1&model=2
As you can see model is repeated multiple times, I would like the parameters following the first model to be model2, model3.......etc.
I've tried putting it in a for loop:
for ($i=0; $i <count($array) ; $i++) {
$args = array
(
'pricefrom' => $fromval,
'priceto' => $toval,
'model'.$i => $array
);
}
but this just gives me :
page2.php?pricefrom=10000&priceto=60000&model1=1&model1=2
You can use the second parameter in http_build_query to prefix the numerical keys with a string:
$args = array
(
'pricefrom' => $fromval,
'priceto' => $toval
);
$args += $array; // merge the two arrays together
$params = http_build_query($args, 'model', '&'); // use a second arg for prefix.
However, I do not recommend to create separate names for variables like this. Better to use &model[]=1&model[]=2. See Passing arrays as url parameter
There was nothing wrong with your original code except that you broke it with the call to preg_replace.
if(!empty($_POST['modelcheck'])){
foreach($_POST['modelcheck'] as $selected){
$models[] = $selected;
}
}
$args = [
'pricefrom' => $fromval,
'priceto' => $toval,
'model' => $models,
];
$params = http_build_query($args);
header("Location: ../page2.php?" . $params);
Now, in page2.php you just use $_GET['model'] as an array.
<?php
foreach ($_GET['model'] as $model) {
printf('%s<br/>', $model);
}
Your $args variable should look like:
$args = array (
'pricefrom' => $fromval,
'priceto' => $toval,
'model' => $array
);
UPD
Use preg_replace for replace html special chars if you want to use http_build_query with multiple params.
$query = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '[]=', http_build_query($args));
You will receive an array by accessing to $_GET['model']

Get Value from Array as Array Key

How do I recursively get value from array where I need to explode a key?
I know, it's not good the question, let me explain.
I got an array
[
"abc" => "def",
"hij" => [
"klm" => "nop",
"qrs" => [
"tuv" => "wxy"
]
]
]
So, inside a function, I pass:
function xget($section) {
return $this->yarray["hij"][$section];
}
But when I want to get tuv value with this function, I want to make section as array, example:
To get hij.klm value (nop), I would do xget('klm'), but to get hij.klm.qrs.tuv, I can't do xget(['qrs', 'tuv']), because PHP consider $section as key, and does not recursively explode it. There's any way to do it without using some ifs and $section[$i] ?
function xget($section) {
return $this->yarray["hij"][$section];
}
that one is static function right?
you can do that also for this
function xget($section) {
if(isset($this->yarray["hij"][$section])){
return $this->yarray["hij"][$section];
}elseif(isset($this->yarray["hij"]["klm"]["qrs"][$section])){
return $this->yarray["hij"]["klm"]["qrs"][$section];
}
}
as long as the key name between two of them are not the same.
You could use array_walk_recursive to find tuv's value regardless of the nested structure:
$tuv_val='';
function find_tuv($k,$v)
{
global $tuv_val;
if ($k=='tuv')
$tuv_val=$v;
}
array_walk_recursive($this->yarray,"find_tuv");
echo "the value of 'tuv' is $tuv_val";
try my code
<?php
$array = array(
'aaa' => 'zxc',
'bbb' => 'asd',
'ccc' => array(
'ddd' => 'qwe',
'eee' => 'tyu',
'fff' => array(
'ggg' => 'uio',
'hhh' => 'hjk',
'iii' => 'bnm',
),
),
);
$find = '';
function xget($key){
$GLOBALS['find'] = $key;
$find = $key;
array_walk_recursive($GLOBALS['array'],'walkingRecursive');
}
function walkingRecursive($value, $key)
{
if ($key==$GLOBALS['find']){
echo $value;
}
}
xget('ggg');
?>

if one array element similar to request variable, then how to fetch another elements of array

I am asking Similar question compare request values to array - it doesn't work to me, my scenario is totally different
$mkt = array(
array(
'title' => "Photos",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'test'
),
array(
'title' => "code",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'main'
),
array(
'title' => "code",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'main'
));
I am having logic issue in this problem, problem is i am getting value via $_REQUEST variable and then i compare this request value to array pkg element. If comparison is true then i want to get another elements except to matched one. In this as suggested, i am using unset to remove the key of element which is matched and all array point to new variable, it working but not for first element of array, it shows null when i compare request variable to first element of array:
$mkt = array();
$newArray = $mkt;
foreach ($newArray as $key => $value ) {
if (in_array($pn, $mkt, true)) {
unset($newArray[$key]);
}
}
$rand_ad = array_rand( $newArray, 1 );
echo json_encode( $newArray[$rand_ad] );
Please have a look on this issue very grateful to me.
Loop in each value, if $pn is equal with that loop's pkg then unset than unset that element:
$pn = 'main';
$newArray = $mkt;
foreach ($newArray as $key => $val) {
if ($pn == $val['pkg']) {
unset($newArray[$key]);
}
}
echo json_encode($newArray);
// [{"title":"Photos","iconlink":"http:\/\/example.com\/xyz.png","pkg":"test"}]

How to create an array for JSON using PHP?

From PHP code I want to create an json array:
[
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"}
]
How can I do this?
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
...
etc.
After that.
json_encode($associativeArray);
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
That's how I am able to do with the help of solution given by #tdammers below.
The following line will be placed inside foreach loop.
$array[] = array('power' => trim("Some value"), 'time' => "time here" );
And then encode the array with json encode function
json_encode(array('newvalue'=> $array), 200)
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.
<?php
// define a JSON Object class
class jsonOBJ {
private $_arr;
private $_arrName;
function __construct($arrName){
$this->_arrName = $arrName;
$this->_arr[$this->_arrName] = array();
}
function toArray(){return $this->_arr;}
function toString(){return json_encode($this->_arr);}
function push($newObjectElement){
$this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
}
function add($key,$val){
$this->_arr[$this->_arrName][] = array($key=>$val);
}
}
// create an instance of the object
$jsonObj = new jsonOBJ("locations");
// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));
$jsonObj->add("location","TestLoc3"); // from key:val pairs
echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>
Will output:
Array
(
[locations] => Array
(
[0] => Array
(
[location] => TestLoc1
)
[1] => Array
(
[location] => TestLoc2
)
[2] => Array
(
[location] => TestLoc3
)
)
)
{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}
To iterate, convert to a normal object:
$myObj = $jsonObj->toArray();
Then:
foreach($myObj["locations"] as $locationObj){
echo $locationObj["location"] ."<br />";
}
Outputs:
TestLoc1 TestLoc2 TestLoc3
Access direct:
$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];
A practical example:
// return a JSON Object (jsonOBJ) from the rows
function ParseRowsAsJSONObject($arrName, $rowRS){
$jsonArr = new jsonOBJ($arrName); // name of the json array
$rows = mysqli_num_rows($rowRS);
if($rows > 0){
while($rows > 0){
$rd = mysqli_fetch_assoc($rowRS);
$jsonArr->push($rd);
$rows--;
}
mysqli_free_result($rowRS);
}
return $jsonArr->toArray();
}

Categories