php array to javascript object - php

I have some case like this:
I have json data:
[{
"1377412272": {
"user_id": "1374050643",
"date": "2013-08-24",
"ip": "::1"
}
},
{
"1377412279": {
"user_id": "1374050643",
"date": "2013-08-25",
"ip": "::1"
}
}
, {
"1377412287": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
}, {
"1377413058": {
"user_id": "1374050643",
"date": "2013-08-25",
"ip": "::1"
}
},
{
"1377413069": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
}
, {
"1377413074": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
},
{
"1377413079": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
}
]
An then, I have convert to array PHP
$newArr = array();
foreach ($view['con'] as $key => $value) {
foreach ($value as $k => $v) {
if (isset($newArr[$v['user_id']][$v['date']])) {
$newArr[$v['user_id']][$v['date']]++;
}
else
$newArr[$v['user_id']][$v['date']] = 1;
$newArr[$v['user_id']][$v['date']] = isset($newArr[$v['user_id']][$v['date']]) ? $newArr[$v['user_id']][$v['date']]++ : 1;
}
}
Script above have result in json_encode with structure like this:
Array
(
[A] => Array
(
[2013-08-24] => 1
[2013-08-25] => 2
)
[B] => Array
(
[2013-08-25] => 4
)
)
and finally, I want it to be javascript object
[
["date","A","B"],
[2013-08-24,1,0],
[2013-08-25,2,4]
]
How to make it?...

To get output like this yo should do
$countArr = array();
foreach ($data as $key => $value)
{
foreach ($value as $k => $v)
{
if (isset($countArr[$v['date']][$v['user_id']]))
{
$countArr[$v['date']][$v['user_id']]++;
}
else
{
$countArr[$v['date']][$v['user_id']] = 1;
}
}
}
$newArr = array();
foreach ($countArr as $date => $val)
{
$row = array($date);
$newArr[] = array_merge(array($date), array_values($val));
}
echo "<pre>";
print_r($newArr);
echo json_encode($newArr)
If you print out $newArr it will look like this
Array
(
[0] => Array
(
[0] => 2013-08-24
[1] => 1
)
[1] => Array
(
[0] => 2013-08-25
[1] => 2
[2] => 4
)
)
json_encode will output
[["2013-08-24",1],["2013-08-25",2,4]]

I'm afraid you need to code everything manually.
One (not too simple) solution is this:
<?php
$ori_list = array(
'A'=> array(
'2013-08-24' => 1,
'2013-08-25' => 2,
),
'B'=> array(
'2013-08-24' => 3,
),
);
$modif_list = array();
// prepare the header
$header = array('date');
foreach($ori_list as $key=>$val){
if(!array_key_exists($key, $header)){
$header[] = $key;
}
}
$modif_list[] = $header;
// prepare the date_list
$date_list = array();
foreach($ori_list as $key=>$val){
foreach($val as $date=>$num){
// add the initial row for every date
$registered = false;
foreach($date_list as $date_row){
if($date_row[0] == $date){
$registered = true;
break;
}
}
if(!$registered){
$date_row = array($date);
for($i=0; $i<count($header)-1; $i++){
$date_row[] = 0;
}
$date_list[] = $date_row;
}
// put the right value to the right row
$first_index = 0;
$second_index = 0;
for($i=1; $i<count($header); $i++){
if($header[$i] == $key){
$second_index = $i;
break;
}
}
for($i=0; $i<count($date_list); $i++){
if($date == $date_list[$i][0]){
$first_index = $i;
break;
}
}
$date_list[$first_index][$second_index] = $num;
}
}
$modif_list[] = $date_list;
echo 'The PHP';
echo '<pre>';
var_dump($modif_list);
echo '</pre>';
echo 'The JSON';
echo '<pre>';
echo json_encode($modif_list);
echo '</pre>';
?>
The code will produce something like this (which I hope is what you want):
The PHP
array(2) {
[0]=>
array(3) {
[0]=>
string(4) "date"
[1]=>
string(1) "A"
[2]=>
string(1) "B"
}
[1]=>
array(2) {
[0]=>
array(3) {
[0]=>
string(10) "2013-08-24"
[1]=>
int(1)
[2]=>
int(3)
}
[1]=>
array(3) {
[0]=>
string(10) "2013-08-25"
[1]=>
int(2)
[2]=>
int(0)
}
}
}
The JSON
[["date","A","B"],[["2013-08-24",1,3],["2013-08-25",2,0]]]

PHP
$arr = array("id"=>"1");
json_encode($arr);
Javascript + PHP
var json = jQuery.parseJSON(<?=$arr?>);
var id = json.id;

I think this is what you want
$newArray = array
(
"A" => array
(
"2013-08-24" => 1,
"2013-08-25" => 2
),
"B" => array
(
"2013-08-25" => 4
)
);
$uids=array();
$da = array();
foreach($na as $uid => $value)
{
$uids[] = $uid;
foreach($value as $date => $count)
{
$da[$date][$uid]=$count;
}
}
$ra = array(array("date"));
foreach($uids as $uid)
{
$ra[0][] = $uid;
}
$i = 1;
foreach($da as $date => $value)
{
$ra[$i][] = $date;
foreach($uids as $uid)
{
if(array_key_exists($uid,$value))
{
$ra[$i][] = $value[$uid];
}
else
{
$ra[$i][] = 0;
}
}
$i++;
}
print(json_encode($ra));
Output:
[["date","A","B"],["2013-08-24",1,0],["2013-08-25",2,4]]

In php, lets call it array.php:
// Your final statment of your array.php script must be an echo statment to send the array to jQuery
$ar = array('item1' => 'value1');
$ret_val['a'] = $ar;
echo json_encode($ret_val);
In jQuery (for example, in the callback of $.post, but you can use $.ajax as well)
$.post("/path/to/array.php,
null, // not passing any values to array.php
function(data) {
console.log (data.a.item1); // writes 'value1' to the console
// (note that the 'a' in data.a.item1 in jQuery is the same as the 'a' in $ret_val in PHP)
},
"json");
}
Then you deal with the return value anyway you like, including creating the final object you seek.

Related

PHP JSON Multi-dimensional array outputting only 1 result

I have been stumped on this for hours. I need to get the initial key of the array and the id. However I am only getting 1 result returned back.
Below is example code and also here is a link - https://3v4l.org/HdMtA
In short the expected output should be.
key 11111111 id val_somevalue5555
key 2222222 id val_somevalue25
I am only getting one result.
key 11111111 id val_somevalue5555
.
$json = '[{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $value)
{
$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);
Any help would be appreciated not sure if its the format of the json or what.
You are iterating the wrong thing.
Using print_r() to view the contents of the decoded array shows us that the thing you want to iterate over is - in fact - wrapped in another array.
print_r($jsonarr) returns this:
Array
(
[0] => Array
(
[11111111] => Array
(
[id] => val_somevalue5555
[customer] => Array
(
[32312] => Array
(
[name] => jane doe
)
)
)
[2222222] => Array
(
[id] => val_somevalue25
[customer] => Array
(
[32312234] => Array
(
[name] => jane doe
)
)
)
)
)
So, what you have is a JSON object wrapped in JSON array with said object being the only item inside it.
You want to either:
a) Get rid of those [ and ] things at the beginning and the end of your JSON, or... (if you don't have control over that JSON)
b) Iterate the inner object (PHP represents it as associative array):
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr[0] as $key => $value) {
$newarr[] = ['key' => $key, 'id' => $value['id']];
}`
var_dump($newarr);
Behold: https://3v4l.org/qCvRd
Change your loop to use the key from the foreach loop itself: Like this
foreach($jsonarr as $key => $value)
{
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']]; //this seems off but what do I know.
}
PHP uses a copy ( or reference?) of the array for Foreach, it can produce some unexpected things to happen. It does some spooky voodoo stuff some times, if you ever try editing the array structure while using reference in foreach such as foreach($var as $k => &$v ) look out. I swear one time it was like phantom items in the array ... lol
You need to change in you json structure and then make necessary changes which I mentioned below
$json = '{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $key=> $value)
{
$newarr[] = ['key' => $key, 'id' => $value['id']];
}
var_dump($newarr);
Are you looking this o/p:
$json = '[{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr[0] as $key => $value)
{
//echo "<br />".$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value['id']];
}
var_dump($newarr);
Output:
array(2) {
[0]=>
array(2) {
["key"]=>
int(11111111)
["id"]=>
string(17) "val_somevalue5555"
}
[1]=>
array(2) {
["key"]=>
int(2222222)
["id"]=>
string(15) "val_somevalue25"
}
}
Or you can change the json structure as ankit patel said and follow his code...
Add another foreach to loop the elements of [0] if you will have more than this.
foreach($jsonarr as $value)
{
foreach($value as $key => $val){
$newarr[] = ['key' => $key, 'id' => $val['id']];
}
}
Result
array(2) {
[0]=>
array(2) {
["key"]=>
int(11111111)
["id"]=>
string(17) "val_somevalue5555"
}
[1]=>
array(2) {
["key"]=>
int(2222222)
["id"]=>
string(15) "val_somevalue25"
}
}
Test here

PHP - How can I create a recursive function?

My array:
array(1) {
["farm"] => array(1) {
["animals"] => array(1) {
[horses] => array(4) {
["fred"] => string(4) "fred"
["sam"] => string(4) "sam"
["alan"] => string(4) "alan"
["john"] => string(4) "john"
}
}
}
}
My function (created by #FrayneKonok)
$id = "2";
$search = "horses";
get_values($arr);
function get_values($arr, $id) {
global $search;
foreach($arr as $key => $value) {
if($key == $search) {
if(is_array($value)) {
echo(join("<a href='mypage.php?id=".$id."&dir=".$value."'><li>",array_keys($value)));
echo("</li></a>");
} else {
echo($value);
}
} else {
get_values($value);
}
}
}
get_values($array,$id);
The result is:
"fred"
<li>sam</li>
<li>alan</li>
<li>john</li>
The result I'm looking for:
<li>fred</li>
<li>sam</li>
<li>alan</li>
<li>john</li>
Another example is when i use if($search = "farm") my result becomes:
"animals"
When the result I'm looking for is:
<li>animals</li>
Online link
Array and input, function call
$arr = array("farm" =>
array("animals"=>
array("horses" =>
array("fred" => "fred",
"sam" => "sam",
"alan" => "alan",
"john" => "john")
)
)
);
$search = 'farm';
get_values($arr);
Function:
function get_values($arr){
global $search;
foreach($arr as $key => $value){
if($key == $search){
if(is_array($value)){
$keys = array_keys($value);
if(count($keys) > 1){
for($i = 0; $i < count($keys); $i++){
echo '<li>'.$keys[$i].'</li>';
}
}else{
echo '<li>'.$keys[0].'</li>';
}
}
else{
echo $value;
}
}else{
get_values($value);
}
}
}
Output
<li>animals</li>
Also tested for the horses.
I suggest using another foreach
Instead of
if(is_array($value)){
echo join("<a href='mypage.php?id=".$id."&dir=".$value."'><li>",array_keys($value));
echo "</li></a>";
}
Use
if(is_array($value)){
foreach( $value as $k => $v ) {
echo "<a href='mypage.php?id=".$id."&dir=".$k."'><li>".$k."</li></a>\n";
}
}
Also don't forget to pass $id each time
The whole thing becomes:
$arr = array( "farm"=> array( "animals"=> array( "horses"=> array( "fred" => "fred", "sam" => "sam", "alan" => "alan", "john" => "john" ) ) ) );
$id = "2";
$search = "horses";
get_values($arr, $id); // <-- pass $id here
function get_values($arr, $id){
global $search;
foreach($arr as $key => $value){
if($key == $search){
if(is_array($value)){
foreach( $value as $k => $v ) {
echo "<a href='mypage.php?id=".$id."&dir=".$k."'><li>".$k."</li></a>\n";
}
}
else{
echo $value;
}
}else{
get_values($value, $id ); // <-- pass $id here to
}
}
}

Trying create an associative array?

I have an array
Array
(
[0] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 1 BIMESTRE
)
[1] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 2 BIMESTRE
)
[2] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] =>3 BIMESTRE
)
)
Now I'm trying create an associative array to return JSON something like this:
"Materia":[{"descricao":"ARTE", "Notas":["1 BIMESTRE":10.00, "2 BIMESTRE":10.00, "3 BIMESTRE":10.00]}]
I don't know how I could create this associative array to this JSON result from this array that I'm posting.
I'm trying create like this but the result what I need does not return
$notas = '';
$materia = '';
foreach($lista as $value){
if($value["M_DESCRICAO"] != $materia){
$materia = $value["M_DESCRICAO"];
}
$notas = array("Descricao"=>$materia, "Notas"=>array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
$result = array("Materia"=>array($notas));
echo json_encode($result);
The result to what I'm trying is
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": {
"3 BIMESTRE": "10.00"
}
}
]
}
How could I create this associative array to return this JSON like I need ?
Edit
$notas = array();
$materia = '';
$materia_array = array();
foreach($lista as $value){
if($materia == ''){
$materia = $value["M_DESCRICAO"];
}
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas)));
$notas = array();
$materia = $value["M_DESCRICAO"];
}else{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
Result
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": [
{
"1 BIMESTRE": "10.00"
},
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "10.00"
}
]
},
{
"Descricao": "C.SOCIAIS",
"Notas": [
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "9.50"
}
]
},
{
"Descricao": "CIƊNCIAS E P. S.",
"Notas": [
{
"2 BIMESTRE": "9.50"
},
{
"3 BIMESTRE": "10.00"
}
]
}
]
}
I've refactored your last edit to remove some code duplication and complexity.
$result = array();
foreach ($lista as $value) {
$materia = $value['M_DESCRICAO'];
if (!isset($result[$materia])) {
$result[$materia] = array(
'Descricao' => $materia,
'Notas' => array()
);
}
$result[$materia]['Notas'][] = array(
$value['PE_DESCRICAO'] => $value['NT_NOTAFINAL']
);
}
$result = array('Materia' => array_values($result));
echo json_encode($result);
In addition to my comment, this would be the code to push all notes to an array as long as the M_DESCRICAO does not change, so the starting array $lista needs to be ordered first. Is this what you were after (code is not tested, office computer :-))?
$notas = $materia = null;
$result = $tmp = array();
$len = count($lista);
for ($i=0;$i<$len;$i++) {
$notas = array();
$materia = $lista[$i]["M_DESCRICAO"];
while (($materia == $lista[$i+1]["M_DESCRICAO"]) && ($i < ($len -1))) {
$notas[$lista[$i]["PE_DESCRICAO"]] = $lista[$i]["NT_NOTAFINAL"];
$i++;
}
// now $notas holds all corresponding entries
$tmp[] = array("Descricao"=>$materia, "Notas" => $notas);
}
$result = array("Materia"=>array($tmp));
echo json_encode($result);
I worked out an untested (there might be some errors, but logically it should work) piece of code, but it might help you:
$notas;
$materia = '';
$materia_array;
foreach($lista as $value){
if($materia == '')
$materia = $value["M_DESCRICAO"];
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas));
unset($notas); //<--------
$notas = array();//<--------
$materia = $value["M_DESCRICAO"];
}
else
{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]))
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
This should work for multiple M_DESCRICAO values

Correct encoding for JSON numbers in PHP

Let's say I have such JSON:
{
id: 1,
somevalue: "text"
}
and I want to create this JSON by PHP function json_encode. I can pretty easy get this JSON in form:
{
"id": "1",
"somevalue": "text"
}
or, using JSON_NUMERIC_CHECK, in form where "id" will be numeric, but "somevalue" can be either numeric or text, depend on its content.
How can I make JSON where "somevalue" always be in text format (with quotes). I'll parse it by other language, where it is important.
Make sure values you want to be non string (like int or boolean) are entered as such into your source array:
<?php
$a = array('id' => 1, 'really' => true, 'somevalue' => 'text');
var_dump( json_decode( json_encode( $a ) ) );
gives expected:
object(stdClass)#1 (2) {
["id"]=>
int(1)
["really"]=>
bool(true)
["somevalue"]=>
string(4) "text"
}
EDIT
If you want it always to be strings, then put strings in your array in first place:
<?php
$a = array('id' => '1', 'really' => 'true', 'somevalue' => 'text');
var_dump( json_decode( json_encode( $a ) ) );
would give
object(stdClass)#1 (3) {
["id"]=>
string(1) "1"
["really"]=>
string(4) "true"
["somevalue"]=>
string(4) "text"
}
but that kills the whole purpose of having different variable types.
Of you can convert your array prior json encoding:
<?php
$a = array('id' => 1, 'really' => true, 'somevalue' => 'text');
$tmp = array();
foreach( $a as $key=>$val ) {
$tmp[$key] = (string)$val;
}
var_dump( json_decode( json_encode( $tmp ) ) );
would give in the end:
object(stdClass)#1 (3) {
["id"]=>
string(1) "1"
["really"]=>
string(1) "1"
["somevalue"]=>
string(4) "text"
}
To make somevalue always in "text" format:
$somevalue1 = 1;
$somevalue2 = "text";
$json1 = array("id" => 1, "somevalue" => (string) $somevalue1);
$json2 = array("id" => 1, "somevalue" => (string) $somevalue2);
echo json_encode($json1); // outputs {"id":1,"somevalue":"1"}
echo json_encode($json2); // outputs {"id":1,"somevalue":"text"}
On PHP> 5.3.3., you can use json_decode($array, JSON_NUMERIC_CHECK);
If you do not have PHP 5.3.3 or more I wrote this recursive function:
function json_encode_with_numbers($array) {
if(is_array($array)) {
if(count($array)>0 && array_keys($array) !== range(0, count($array) - 1)) {
echo '{';
$isFirst = true;
foreach($array as $key=>$item) {
if(!$isFirst) {
echo ",";
}
echo '"'.$key.'":';
json_encode_with_numbers($item);
$isFirst = false;
}
echo '}';
} else {
echo '[';
$isFirst = true;
foreach($array as $item) {
if(!$isFirst) {
echo ",";
}
json_encode_with_numbers($item);
$isFirst = false;
}
echo ']';
}
} else {
if(is_numeric($array)) {
echo $array;
} elseif ($array == null) {
echo "null";
} else {
echo '"'.str_replace(array('"', '\\'), array('\"', '\\\\'), $array).'"'; // escape special chars
}
}
}

PHP Reconstruct Array

I need to reconstruct an array. Here is the original array:
array(8) {
[0] => array(1)
{
["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D"
}
[1] => array(1)
{
["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528"
}
[2] => array(1)
{
["L_STATUS0"] => string(9) "Completed"
}
[3] => array(1)
{
["L_STATUS1"] => string(9) "Completed"
}
}
I would like to reconstruct it to be as such:
array(2) {
[0] => array(2)
{
["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D"
["L_STATUS0"] => string(9) "Completed"
}
[1] => array(1)
{
["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528"
["L_STATUS1"] => string(9) "Completed"
}
}
Notice that the KEYS both match with the numeric representation... Is this at all possible?
edit:
here is my code I am using:
foreach($comparison as $key => $val) {
$findme1 = 'L_TRANSACTID'.$i++;
$findme2 = 'L_STATUS'.$c++;
$arrDisable = array($findme1,$findme2);
if( in_array($key, $arrDisable ) ) {
unset( $comparison[ $key ][$val]);
}
if( in_array($key, $arrDisable) ) {
unset( $comparison[ $key ][$val]);
}
}
Try this
$labels = array('L_TRANSACTIONID', 'L_STATUS');
$res = array();
foreach($arr as $val) {
$key = str_replace($labels, '', key($val));
$res[$key] = isset($res[$key]) ? array_merge($res[$key], $val) : $val;
}
print_r($res);
http://codepad.org/MwqTPqtA
If you are certain the the vector cointains pairs L_TRANSACTIONIDn / L_STATUSn keys,that is to say, for each transactionID, there is a corresponding status, what you can do, is to get the number of id/status records (which should equal the length of the initial array, divided by two), and compose the resultin keys, by increasing the current element count.
Could look something like this:
$numItems = sizeof($myInitialArray) / 2;
$newArray = array();
for($i = 0; $i < $numItems; $i++)
{
$itemID = $i * 2; // since we're getting id/status pairs, we're using a step equal to 2
$newArray[] = array(
("L_TRANSACTIONID" . $i) => $myInitialArray[$itemID], // this is the id value
("L_STATUS" . $i) => $myInitialArray[$itemID + 1] // this is the status for that id
);
}
Hope this helps. Have a great day!

Categories