Reputation:
I need some help.I need to check weather the key value is present inside the json array or not using PHP but its throwing some warning message and no value is coming. I am explaining my code below.
$mainArr=array(array("type"=>1,"name"=>"hello"),array("type"=>1,"name"=>"hii"));
//echo json_encode($mainArr);
foreach ($mainArr as $v) {
if(!in_array(1, $v['type'])){
$result['primary'][]=array();
}else{
$result['primary'][]=$v;
}
if(!in_array(2, $v['type'])){
$result['secondary'][]=array();
}else{
$result['secondary'][]=$v;
}
}
echo json_encode($result);
Here I need to check if type==2
is not present inside that array it should return blank array but its throwing the below message.
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 5
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 10
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 5
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 10
{"primary":[[],[]],"secondary":[[],[]]}
Please help me to resolve this issue.
Upvotes: 0
Views: 113
Reputation: 440
Use array_search() function. For example:
foreach ($mainArr as $v) {
if (!array_search('1', $v)) {
$result['primary'][]=array();
} else {...}
Upvotes: 0
Reputation: 487
$mainArr=array(array("type"=>1,"name"=>"hello"),array("type"=>1,"name"=>"hii"));
//echo json_encode($mainArr);
foreach ($mainArr as $v => $values) {
if(!in_array(1, $values['type'])){
$result['primary'][]=array();
}else{
$result['primary'][]=$values;
}
if(!in_array(2, $values['type'])){
$result['secondary'][]=array();
}else{
$result['secondary'][]=$values;
}
}
echo json_encode($result);
Upvotes: 0
Reputation: 147
You search element in an array element not an array.
<?php
$mainArr = array(
array(
"type" => 1,
"name" => "hello"
),
array(
"type" => 1,
"name" => "hii"
)
);
//echo json_encode($mainArr);
foreach ($mainArr as $v) {
if (!in_array(1, $v)) {
$result['primary'][] = array();
} else {
$result['primary'][] = $v;
}
if (!in_array(2, $v)) {
$result['secondary'][] = array();
} else {
$result['secondary'][] = $v;
}
}
echo json_encode($result);
?>
Upvotes: 0
Reputation: 1445
You are using the PHP's in_array function on a scalar value.
$v['type'] is an integer, a simple comparaison like
1 === $v['type']
will do the job
Upvotes: 1