I have a json value like this :
{
"A":{"id":"1","checked":false},
"B":{"id":"2","checked":true},
"C":{"id":"3","checked":true}
}
I just need id and checked values. I don't know what value is placed in A,B,C.
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($chboxs, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
// echo "$key:\n";
} else {
//echo "$key => $val\n";
if($val == true){
$val = 1 ;
}else{
$val = 0 ;
}
$ch = array();
$ch['isvisible'] = $val;
$this->m_general->edit('coupon_properties' , $ch , array('id'=>$key));
}
}
It doesn't work fine.
Just use json_decode:
$arr = json_decode('{
"A":{"id":"1","checked":false},
"B":{"id":"2","checked":true},
"C":{"id":"3","checked":true}
}');
So this will give you as:
Array (
A => Array (
id => 1,
checked => false
)
B => ...
)
You can get it like:
$arr["A"]["id"]; // 1
$arr["B"]["checked"]; // true
So, to iterate, you can use:
foreach ($arr as $ar) {
echo $ar["id"], $ar["checked"];
}
Related
I need to modify the data structure of json array list as per some key value using PHP. I am explaining my code below.
<?php
$output=array(
array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA001"
),array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA002"
),array(
"first_name"=>"Rama",
"last_name"=>"Nayidu",
"reg_no"=>13,
"paper_code"=>"BA001"
)
);
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$result[]=array(
"name"=>$value["first_name"].' '.$value['last_name'],
"reg_no"=>$value['reg_no'],
"paper1"=>$value['paper_code'],
"paper2"=>"",
"paper3"=>"",
"paper4"=>""
);
}
}
The output of the input array is given below.
// Output:
[
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA001"
},
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA002"
},
{
"first_name":"Rama",
"last_name":"Nayidu",
"reg_no":13,
"paper_code":"BA001"
}
];
The above is my array list. Here I need to modify the all row value by reg_no means if there are multiple rows including same reg_no then those will merge with joining the both name and my expected output should like below.
expected output:
[
{
'name':"robin sahoo",
"reg_no":12,
"paper1":"BA001",
"paper2":"BA002",
"paper3":"",
"paper4":""
},
{
'name':"Rama Nayidu",
"reg_no":13,
"paper1":"BA001",
"paper2":"",
"paper3":"",
"paper4":""
}
]
Here paper1,paper2,paper3,paper4 will be selected serially means suppose same reg_no=12 has first row paper_code= BA001 then it will be paper1=BA001 and second row paper_code=BA002 then it will be paper2=BA002 and so on. Here I am using PHP to map this array.
Try the following, Let me know..
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
$temp=array();
if(!empty($output)){
foreach ($output as $key => $value) {
if(isset($temp[$value['reg_no']])){
if(empty($temp[$value['reg_no']]["paper1"]) || $temp[$value['reg_no']]["paper1"] == ""){
$temp[$value['reg_no']]["paper1"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper2"]) || $temp[$value['reg_no']]["paper2"] == ""){
$temp[$value['reg_no']]["paper2"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper3"]) || $temp[$value['reg_no']]["paper3"] == ""){
$temp[$value['reg_no']]["paper3"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper4"]) || $temp[$value['reg_no']]["paper4"] == ""){
$temp[$value['reg_no']]["paper4"] = $value['paper_code'];
}
}else{
$temp[$value['reg_no']] = array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}
}
if(!empty($temp)){
foreach ($temp as $key => $value) {
$result[] = $value;
}
}
This Code May help you
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$output[$key]=array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}echo "<pre>";print_r($output);
?>
You can try with this
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'name' => $name,
'reg_no' => $value['reg_no'],
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'];
}
$result = array_values($result); // reindex result array
$result = json_encode($result); // Encode to json format
print_r($result); // print result
This assumes that first_name and last_name is always same for each reg_no
I'm trying to loop through a JSON that I post to my PHP backend. The JSON looks like this:
[
{
"number":"5613106"
},
{
"number":"56131064"
},
{
"number":"56131063"
}
]
I post it from Postman like so:
I want to be able to print each number that I've posted individually using
echo $number;
Right now when I use the following it just prints the last number:
$number = $json['number'];
echo $number;
My function:
public function check_users_post()
{
$json = $this->request->body;
print_r($json);
$this->response($json, REST_Controller::HTTP_OK);
}
The output:
Array
(
[0] => Array
(
[number] => 5613106
)
[1] => Array
(
[number] => 56131064
)
[2] => Array
(
[number] => 56131063
)
)
Hope this generic iterator will help you.
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Use
json_decode()
PHP built in function for decoding json back to PHP variable or array and then loop through each index and print number.
Got it done like this:
public function check_users_post()
{
$json = $this->request->body;
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($json),
RecursiveIteratorIterator::SELF_FIRST);
$phone_numbers = "";
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
} else {
$phone_numbers = "$phone_numbers" . ", " . "$val";
}
}
$phone_numbers = substr($phone_numbers, 2);
$phone_numbers = "(" . $phone_numbers . ")";
$query = $this->db->query("SELECT * FROM users WHERE user_number in $phone_numbers;");
$result = $query->result();
$this->response($result, REST_Controller::HTTP_OK);
if (mysql_num_rows($result)==0) {
$data = [ 'message' => 'No users returned'];
$this->response($data, REST_Controller::HTTP_BAD_REQUEST);
} else {
$this->response($result, REST_Controller::HTTP_OK);
}
}
Description
First stringify your JSON, than use JSON_DECODE() function which gives you the array afterwards iterate on this array using foreach loop which will give you the each key which you want to echo.
Code
$str = '[
{
"number":"5613106"
},
{
"number":"56131064"
},
{
"number":"56131063"
}
]';
$array = json_decode($str, true);
echo "<pre>";
foreach ($array as $key => $key_value) { // then loop through it
echo "<br>";
echo $array[$key]['number'];
echo "<br>";
}
Output
5613106
56131064
56131063
Suppose, i have the fallowing json:
{
"foo.bar": 1
}
and i want to save this like this:
$array["foo"]["bar"] = 1
but i also can have more than 2 "parameters" in string. For example:
{
"foo.bar.another_foo.another_bar": 1
}
and i want to save this same way.
$array["foo"]["bar"]["another_foo"]["another_bar"] = 1
Any ideas how can i do that in case that i don't know how many parameters i have?
This is far from the nicest solution, but I've been programming all day so I'm a little tired, but I hope it gives you something to work off, or at least a working solution for the time being.
Here's the IDEone of it working: click
And here's the code:
$json = '{
"foo.bar": 1
}';
$decoded = json_decode($json, true);
$data = array();
foreach ($decoded as $key => $value) {
$keys = explode('.', $key);
$data[] = buildNestedArray($keys, $value);
}
print_r($data);
function buildNestedArray($keys, $value) {
$new = array();
foreach ($keys as $key) {
if (empty($new)) {
$new[$key] = $value;
} else {
array_walk_recursive($new, function(&$item) use ($key, $value) {
if ($item === $value) {
$item = array($key => $value);
}
});
}
}
return $new;
}
Output:
Array
(
[0] => Array
(
[foo] => Array
(
[bar] => 1
)
)
)
Wasn't sure whether your JSON string could have multiples or not so I made it handle the former.
Hope it helps, may come back and clean it up a bit in the future.
Start with a json_decode
Then build a foreach loop to break apart the keys and pass them to some kind of recursive function that creates the values.
$old_stuff = json_decode($json_string);
$new_stuff = array();
foreach ($old_stuff AS $key => $value)
{
$parts = explode('.', $key);
create_parts($new_stuff, $parts, $value);
}
Then write your recursive function:
function create_parts(&$new_stuff, $parts, $value)
{
$part = array_shift($parts);
if (!array_key_exists($part, $new_stuff)
{
$new_stuff[$part] = array();
}
if (!empty($parts)
{
create_parts($new_stuff[$part], $parts, $value);
}
else
{
$new_stuff = $value;
}
}
I have not tested this code so don't expect to just cut and past but the strategy should work. Notice that $new_stuff is passed by reference to the recursive function. This is very important.
Try the following trick for "reformatting" into json string which will fit the expected array structure:
$json = '{
"foo.bar.another_foo.another_bar": 1
}';
$decoded = json_decode($json, TRUE);
$new_json = "{";
$key = key($decoded);
$keys = explode('.', $key);
$final_value = $decoded[$key];
$len = count($keys);
foreach ($keys as $k => $v) {
if ($k == 0) {
$new_json .= "\"$v\"";
} else {
$new_json .= ":{\"$v\"";
}
if ($k == $len - 1) $new_json .= ":$final_value";
}
$new_json .= str_repeat("}", $len);
var_dump($new_json); // '{"foo":{"bar":{"another_foo":{"another_bar":1}}}}'
$new_arr = json_decode($new_json, true);
var_dump($new_arr);
// the output:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
array (size=1)
'another_foo' =>
array (size=1)
'another_bar' => int 1
I have the an array, in which I store one value from the database like this:
$stmt = $dbh->prepare("SELECT token FROM advertisement_clicks WHERE (username=:username OR ip=:ipcheck)");
$stmt->bindParam(":username",$userdata["username"]);
$stmt->bindParam(":ipcheck",$ipcheck);
$stmt->execute();
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So, that gives me: array("token","token");
When I print it:
Array ( [0] => Array ( [token] => 677E2114AA26BA4351A686917652C7E1BA67A32D ) [1] => Array ( [token] => C42190F3D72C5BB6BB6B68488D1D4662A8D2A138 ) )
I then have a loop, that loops all the tokens. In that loop, I try to search for a specific token, and if it that token matches, it will be marked as "seen":
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return $key;
}
}
}
This is my loop:
$icon = "not-seen";
foreach($d as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam == $token){
$icon = "seen";
}
}
However, searchForid() simply returns 0
What am I doing wrong?
Ok, here you can see a PHP fiddle that works
$data = array();
$data[] = array('token'=>'123');
$data[] = array('token'=>'456');
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return true;
}
}
return false;
}
$icon = "not-seen";
foreach($data as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam){
$icon = "seen";
}
}
echo $icon;
It echos 'seen' which is expected since I compare the same array values, now assuming that your $d variable has different tokens, it should still work this way.
That means that your $d array does not contain what you claim it contains, could you print_r this variable and post it in your answer?
I have problem with two arrays:
$pole1 = array(
array("klic"=>"banan", "jmeno"=>"Banán"),
array("klic"=>"pomeranc", "jmeno"=>"Pomeranč"),
);
$pole2 = array(
array("klic"=>"banan"),
);
Now I need foreach data:
foreach ($pole1 as $key => $val){
//all data from $pole
echo $val
//and here if "klic" from $pole1 == "klic" from $pole2
if ($pole2[$key]["klic"] == $pole1["klic"])
echo "YES"; // - **not working**
}
I need to check if data from $pole1 equals data from $pole2 and write some text but I need to write all data from $pole1.
You meant that?
foreach ($pole1 as $key => $val) {
if ( isset($pole2[$key]["klic"] &&
($pole2[$key]["klic"] == $pole1[$key]["klic"]) )
echo "YES";
}
try this
foreach($pole1 as $k1 => $arrays) {
foreach($arrays as $k2 => $val) {
if($pole2[$k1][$k2] == $val) {
// $pole1[$k1][$k2] is equal to $pole2[$k1][$k2]
}
}
This will echo every entry in pole1 and check every entry in pole1 with every entry in pole2.
foreach($pole1 as $val){
echo($val);
foreach($pole2 as $val2){
if($val['klic']==$val2['klic']) echo 'YES';
}
}