Modify generated json from PDO and PHP - php

I will be quick with more code less talk.
I have a mySQL DB and i want to generate json from it with PHP and PDO.
<?php
require("db.php");
$dsn = "mysql:host=localhost;dbname=$dbname";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
$stmt = $pdo->prepare("SELECT * FROM table");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '{"jsons":';
echo json_encode($rows);
echo "}";
?>
The above code will return
{"jsons":[{"date_time":"2012-09-06 20:55:44","name":"theOne","message":"i am god","ip":"","device":"HTC","device_type":"Phone","class":"class1","id":"1"}]}
I want to modify the php code so my json output will be
{"jsons":[{"date_time":"2012-09-06 20:55:44","name":"theOne","message":"i am god","ip":"","devs":{"device":"HTC","device_type":"Phone","class":"class1","id":"1"}}]}
The difference is that i want to nest device,device_type,class and id into devs.
I couldn't do anything or find from google such a task.
Any help will be appreciate.
Thank you.

$push_in_devs = array("device","device_type","class","id") ;
$old_set = json_decode('{"jsons":[{"date_time":"2012-09-06 20:55:44","name":"theOne","message":"i am god","ip":"","device":"HTC","device_type":"Phone","class":"class1","id":"1"}]}') ;
$old_object = $old_set->jsons[0] ;
$new_set = new STDClass() ;
$new_set->jsons = array(0 => new STDClass) ;
$new_object = $new_set->jsons[0] ;
foreach($old_object as $name => $value){
if (!in_array(strtolower($name), $push_in_devs))
$new_object->$name = $value ;
}
$new_object->devs = array() ;
$dev = array() ;
foreach($push_in_devs as $name){
$dev[$name] = $old_object->$name ;
}
$new_object->devs[] = $dev ;
echo json_encode($new_set) ;

Run this block right after the $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); line:
foreach ($rows as $key => $row) {
foreach ($row as $column => value) {
if ($column == 'device' || $column == 'device_type' || $column == 'class' || $column == 'id') {
$row[$key]['devs'][$column] = $value;
} else {
$row[$key][$column] = $value;
}
}
}
This will nest the values underneath the 'devs' key for each row, before proceeding to encode to JSON.

$results = array();
foreach ($rows as $row) {
$result = array();
foreach ($row as $key => $value) {
if ($key === 'device' || $key === 'device_type'
|| $key === 'class' || $key === 'id') {
$result['devs'][] = $value;
} else {
$result[$key] = $value;
}
}
$results[] = $result;
}
json_encode($results);

Related

MySQLi why am I only getting 1 result?

There are three "BC" in the result_category but I am only getting 1 result. This is for a personality quiz. Please Help. I also tried $query = "SELECT result FROM quiz_map where result_category = 'BC'"; but still, only 1 result is showing.
$result = mysqli_query($link, $query);
$cat_a = $cat_b = $cat_c = $cat_d = $cat_e = 0;
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$cat = $row['category'];
if ($cat == "A") {
$cat_a += 1;
} elseif ($cat == "B") {
$cat_b += 1;
} elseif ($cat == "C") {
$cat_c += 1;
} elseif ($cat == "D") {
$cat_d += 1;
} elseif ($cat == "E") {
$cat_e += 1;
}
}
$array = array('A' => $cat_a, 'B' => $cat_b, 'C' => $cat_c, 'D' => $cat_d, 'E' => $cat_e);
$str = '';
foreach ($array as $i => $value) {
if ($value >= 6) {
$str = $i;
break;
} elseif ($value >= 2) {
$str .= $i;
}
}
$var = sort($array);
$query = "SELECT result FROM quiz_map where result_category = '$str' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo $row[0];
?>
There's many things wrong with your code!
As pointed by #IsThisJavascript and #Cashbee:
You are executing a query with a LIMIT 1 statement, it will only return one record.
As pointed by myself:
Doing echo $row[0] will have the same result, if you are only echoing the first value of the array you can't expect to have multiples can you?
As pointed by #IsThisJavascript:
You need to loop the results array, like so:
while($row = mysqli_fetch_array($result)){
echo $row['result_category'];
}
Consider switching the query from a '=' to a '%like%' statement, to maximize results if you want to get the values that partionaly cointain the string.

How to get all the results where parent is an item from an array

I have an array that consists names of parents ,I want to get all the results where any of the name is a parent.Here is my code.I am not able to get the list of names where parent is equal to the names in district array.
Here is my complete code.
<?php
$functionname = 'core_course_get_categories';
$username = array('key' => 'name', 'value' => '2016');
$params = array('criteria' => array($username));
$server_url = 'localhost/moodle' . '/webservice/rest/server.php' . '?wstoken=' . '9cdaccf3a7ad2f0f94922ccfd02559f4' . '&wsfunction=' . $functionname;
$rest_format = 'json';
require_once('curl.inc');
$curl = new curl;
$rest_format = ($rest_format == 'json') ? '&moodlewsrestformat=' . $rest_format : '';
$resp = $curl->post($server_url . $rest_format, $params);
$res = json_decode($resp);
// drupal_set_message('<pre>'. dpm($res) .'</pre>');
$district = array();
$Ctsc = array();
$School = array();
$Grade = array();
$parent = array();
foreach ($res as $r) {
$a = $r->parent;
$c = $r->name;
if ($a == 0) {
$b = $r->id;
var_export($b);
}
}
foreach ($res as $r) {
if ($r->parent == $b) {
//$dist=$r->name;
$district[] = $r->name;
}
}
$Ctsc[] = $r->description;
$School[] = $r->sortorder;
$Grade[] = $r->depth;
foreach ($res as $r) {
$q = $r->name;
if (in_array($q['parent'], $district)) {
$Ctsc[] = $q->name;
dpm($Ctsc);
}
if ($Ctsc['parent'] == $district) {
dpm($Ctsc);
}
}
Usage of in_array() is wrong.
Instead of
if(in_array($q['parent'] == $district)){ ... }
use
if(in_array($q['parent'], $district)){ ... }

Change the array structure in php

How can i change the test1 array format as like in test2?
$test1 = array(
'size'=>array('V'=>array('V'),'R'=>array('R','R')),
'price'=>array('V'=>array('77'),'R'=>array('88','99')),
'unit'=>array('V'=>array('3'),'R'=>array('3','2')),
'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));
$test2 = array(
'size'=>array('V','R'),
'price'=>array('V'=>array('Black'=>'77'),
'R'=>array('Green'=>'88','Red'=>'99')),
'unit'=>array('V'=>array('Black'=>'3'),
'R'=>array('Green'=>'3','Red'=>'2')),
'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));
Thanks!
With a foreach loop you can change the array structure.
http://php.net/manual/de/control-structures.foreach.php
Something like that should work: its pretty unclear what the rules are to convert from one array to the other in your case.
$test2 = array();
foreach ($test as $type => $array) {
$newArray = array();
foreach ($array as $key => $value) {
if ($key == 'V') {
if ($value == 3) {
$newArray['V'] = array('Black' => 3);
} else if ($value = 2) {
$newArray['V'] = array('Green' => 2);
}
} else if ($key == 'R') {
//....
}
}
$test2[$type] = $newArray;
}
Thanks for the response. and sorry for not being more specific. Actually i wanted all the values in dynamic manner. I constructed a loop :). Thanks!
$myArray = array();
foreach($test as $type => $array){
$k = 0;
foreach ($array as $key => $value) {
if($type == 'size'){
$myArray['size'][] = $key;
}else if($type == 'price' || $type == 'unit' ){
$m = 0;
foreach($value as $vall){
if($type == 'price'){
$myArray['price'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['price'][$myArray['size'][$k]][$m];
}else if($type == 'unit'){
$myArray['unit'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['unit'][$myArray['size'][$k]][$m];
}
$m++;
}
}else if($type == 'color'){
$myArray['color'][] = $value;
}
$k++;
}
}

how to store associative array php MySQL

I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

Categories