How to get a complex value in array? - javascript

This is my JSON array
Array
(
[0] => Array
(
[active] => Y
(
[0] => Array
(
[sub] => 5
)
)
)
)
My question how can I get value 5 in sub by using foreach.

Try this:
foreach ($rs_amount as $result) {
foreach ($result['sub_resource'] as $sub_resource) {
foreach ($sub_resource as $subs) {
echo $subs['sub'] . "<br/>";
}
}
}

Use this
foreach($results['data'] as $result) {
if(is_array($result)) {
print_r($result) ;
echo '<br>';
} else {
echo $result['type'] . '<br>';
}
}

Related

Autocomplete from array and get the corresponding id

Just wondering if someone knows a way to be able to autocomplete an input field after you type 3 letters then also get the id of the corresponding value?
I tried something like this with the UI Jquery:
It works great with the test array, but not with the real array im trying to use. Is it because the format is wrong? I include the array before json_encode and after.
var test = ["1899 Hoffenheim vs Borussia Dortmund", "SD Eibar vs Granada CF", "Fiorentina vs AS Roma"];
var availableTags = <?php echo json_encode($testArray); ?>;
console.log(availableTags);
$( "#test" ).autocomplete({
source: test
});
});
Before json_encode
Array
(
[0] => Array
(
[id] => 33820950
[match] => 1899 Hoffenheim vs Borussia Dortmund
)
[1] => Array
(
[id] => 33820951
[match] => SD Eibar vs Granada CF
)
[2] => Array
(
[id] => 33820952
[match] => Fiorentina vs AS Roma
)
[3] => Array
(
[id] => 33820991
[match] => Hibernian vs Rangers
)
[4] => Array
(
[id] => 33821044
[match] => RKC Waalwijk vs FC Twente
)
[5] => Array
(
[id] => 33821045
[match] => Middlesbrough vs Stoke City
)
[6] => Array
(
[id] => 33821108
[match] => Deportivo La Coruña vs CD Tenerife
)
[7] => Array
(
[id] => 33821138
[match] => Zaglebie Lubin vs Legia Warszawa
)
[8] => Array
(
[id] => 34096342
[match] => Everton vs Arsenal
)
[9] => Array
(
[id] => 34096343
[match] => Aston Villa vs Southampton
)
)
After json_encode
[{"id":"33820950","match":"1899 Hoffenheim vs Borussia Dortmund"},{"id":"33820951","match":"SD Eibar vs Granada CF"},{"id":"33820952","match":"Fiorentina vs AS Roma"},{"id":"33820991","match":"Hibernian vs Rangers"},{"id":"33821044","match":"RKC Waalwijk vs FC Twente"},{"id":"33821045","match":"Middlesbrough vs Stoke City"},{"id":"33821108","match":"Deportivo La Coru\u00f1a vs CD Tenerife"},{"id":"33821138","match":"Zaglebie Lubin vs Legia Warszawa"},{"id":"34096342","match":"Everton vs Arsenal"},{"id":"34096343","match":"Aston Villa vs Southampton"}];
Update:
Sorry, I misunderstood you at first. I guess you want to save all text values of the key match to a json array. So I take your $testArray, loop through it and assign everything to a new array that it matches the format.
Try this:
<?php
$array = [];
$i = 0;
$id = 0;
$ids = '[';
$availableTags = '[';
foreach($testArray as $val) {
$id[] = "\"".$val[$i]['id']."\"";
$array[] = "\"".$val[$i]['match']."\"";
$i++;
}
$id = implode(', ', $id);
$array = implode(', ', $array);
$availableTags .= $array . '];';
$ids = $id . '];';
?>
var availableIds = <?= $ids; ?>
var availableTags = <?= $availableTags; ?>
console.log(availableTags);
$( "#test" ).autocomplete({
source:
return {
label: availableTags,
value: availableIds
};
});
});
Finished working code. Where you can search for the match and both match and the corresponding id gets saved.
<form action="" method="POST" >
<input id="match_search" name="match_search" onChange="this.form.submit()">
<input id="match_id" name="match_id" hidden>
</form>
<?php
if (isset($_POST['match_search'])) {
$match = $_POST['match_search'];
$match_id = $_POST['match_id'];
echo $match.'<br>';
echo $match_id;
}
?>
<script>
var availableMatches = <?=json_encode($testArray); ?>;
$(function() {
$("#match_search").autocomplete({
delay: 0,
source: availableMatches,
select: function(event, ui) {
$('#match_search').val(ui.item.label);
$('#match_id').val(ui.item.value);
return false;
},
focus: function(event, ui) {
$("#match_search").val(ui.item.label);
return false;
}
});
});
</script>

How do I parse this json data in view laravel [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$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";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
run on codepad
I can't believe so many people are posting answers without reading the JSON properly.
If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
To echo the statuses of each person, try this:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
The most elegant solution:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.
Alternatively:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
Try
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.
Try This
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}
Try:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}
More standard answer:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
And the output is:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0
Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.
foreach($json_a as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
# and so on
}
}
}
<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>
Try it:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}
The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}
You have to give like this:
echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>
Which gives the result :
wait
active
I am using below code for converting json to array in PHP,
If JSON is valid then json_decode() works well, and will return an array,
But in case of malformed JSON It will return NULL,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>
If in case of malformed JSON, you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>
If in case of malformed JSON, you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>

PHP dimensional array to Javascript array WITHOUT JSON

I'm trying to convert a PHP multidimensional array to a javascript array WITHOUT using json encoder because of the version of the server.
Exemple of a multidimensional Array :
Array (
[0] => Array (
[0] => 18
[1] => Région Grand EST
[2] => GE )
[1] => Array (
[0] => 17
[1] => Région Grand OUEST / NORD
[2] => GO N )
[2] => Array (
[0] => 25
[1] => Région Grand OUEST / SUD
[2] => GO S )
)
Currently for no multidimensional array i'm using this function :
function js_str($s) {
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array) {
if (is_array($array)) {
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
return '[-1]';
}
But i can't use it for multidimensional, i'm trying to do somthing similar recursively to do it with any size of array.
To get a result like :
myArray = [[18, 'Région Grand EST', 'GE'],[17, 'Grand OUEST / NORD', 'GO N'], [25, 'Région Grand OUEST / SUD', 'GO S']];
It's really hard to find an answer without json_encode, thanks for your help.
(Yes i'm developping on a prehistoric server)
I would approach this problem with a recursive function like this:
function js_array($array) {
if (is_array($array)) {
$temp = array();
$output = '[';
foreach ($array AS $key=>$value) {
$temp[] .= "'$key':" . js_array($value);
}
$output .= implode(',', $temp);
$output .= "]";
} else {
$output .= "'$array'";
}
return $output;
}
What we're doing here is evaluating each element of the array to see if it is also an array. Each level drills down into itself until we are left with simple key:value pairs.
You can edit for special characters or to drop the array keys if you want.
Thx to Danielml01 for his help.
Here the solution used :
function js_array($array) {
if (is_array($array)) {
$temp = array();
$isObject = false;
foreach ($array AS $key=>$value) {
if (is_numeric($key))
$temp[] .= js_array($value);
else {
$isObject = true;
$temp[] .= "'$key':" . js_array($value)."";
}
}
if ($isObject)
$output = "{".implode(',', $temp)."}";
else
$output = "[".implode(',', $temp)."]";
}
else
$output = "'".$array."'";
return $output;
}

JSON Array parsing in PHP and updating in the database

Though this is a textbook problem, but I'm not able to parse from json object. I have a json object coming from a page, and I need to extract the ID,fieldText value so that I can update the table.
Here is how I'm capturing the json and converting it into array, not sure how to extract the values.
if(isset($_POST['postData'])){
$json = json_decode($_POST['postData'],true);
foreach ($json as $key => $value)
{
print_r($key);
//print_r($value);
foreach ($value as $k => $val)
{
//echo "$k | $val <br />";
} }
I need to update the table with [ID] and [fieldText] :
Result should like this::(1:Hello World), (2:The rising Star),(3: Terminator)
My JSON object is like this:
Array(
[fieldName] => Array
(
[0] => fieldText[1]
[1] => fieldText[2]
[2] => fieldText[3]
)
[fieldText] => Array
(
[0] => HelloWorld
[1] => The rising Star
[2] => Terminator
)
[ID] => Array
(
[0] => 1
[1] => 2
[2] => 3
))
Hi it seems that there are three arrays in your JSON, I think it would be better to change the way you generate the JSON to make it simple to understand.
// assumes $arr as the $_POST['postData'] in your case
$arr = array("1"=>"Hello World", "2"=>"The Rising Star", "3"=>"Terminator");
$j = json_encode($arr);
$json = json_decode($j,true);
foreach ($json as $key => $value)
{
echo '('.$key.','. $value.')';
}
The results are :
(1,Hello World)(2,The Rising Star)(3,Terminator)
Hope this can help you.
Hope you can do something like this.
$jsonData = Array(
'Name' => Array
(
0 => 'Text1',
1 => 'Text2',
2 => 'Text3'
),
'Value' => Array
(
0 => 'HelloWorld',
1 => 'The rising Star',
2 => 'Terminator'
),
'ID' => Array
(
0 => 1,
1 => 2,
2 => 3
)
);
$length = count($jsonData['ID']);
for($j=0;$j<$length;$j++) {
echo "(".$jsonData['ID'][$j].": ".$jsonData['Value'][$j].")<br/>";
}
In my opinion you should make your life easier by modifying the json array you receive with $_POST['data'];. If I were in your shoes my json would've been exactly as you need it:
{ 1:'Hello World', 2:'The rising Star',3:'Terminator' }
But if you are not able to change it for any reason I think you could use something like this (basing this example on your code):
$jsonData = json_encode($_POST['json'], true);
$id = $jsonData['ID'];
$fieldText = $jsonData['fieldText'];
$arr = array();
for ($i=0; $i < count($id); $i++) {
$arr[(int) $id[$i]] = $fieldText[$i];
}
var_dump($arr);
Hope this helps you!

How to properly format JSON

I asked a question earlier, which all revolved around a JSON formatting problem. I have a PHP page, which just grabs rows from a MYSQL database, and returns them. However, i'm unsure how to format them so all the columns I get are a set, and for each row, it creates a new set. I'm not sure what is common practice to do to encode things like this.
e.g. this is what I want (if it is even correct):
{ "message": [
{
"chat":"Hello, world!",
"time":"2014-05-09 17:32:00",
"username":"Josue"
},
{
"chat":"This is my second message.",
"time":"2014-05-09 17:32:05",
"username":"Josue"
}
]
}
That way, I can parse using $.parseAJAX, and get access to my data like: data.message[0].chat, and it would return "Hello world!".
Here is what I am currently doing:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = 'chat';
$messages[] = $row['chat'];
$messages[] = 'time';
$messages[] = $row['time_sent'];
$messages[] = 'username';
$messages[] = $row['username'];
}
$loopCount = count($chats);
if(count($messages) > 0){
/*
$sexyJSON = '{message: [';
for($i = 0; $i < $loopCount; $i++){
$sexyJSON .= '{"chat":"'.$chats[$i].'","time":"'.$times[$i].'","username":"'.$usernames[$i].'"},';
}
$sexyJSON = substr($sexyJSON,0,strlen($sexyJSON)-1);
$sexyJSON .= ']}';
$newMessages = $sexyJSON;
echo $sexyJSON;
*/
echo json_encode($messages);
}
When I simply encode my array, it returns something like this:
["chat","Hello, world!","time","2014-05-09 17:32:00","username","Josue","chat","hmmm","time","2014-05-09 17:48:34","username","asdf"]
What would I have to do to group chat with the message, date with the date, and username with the username in a key-value pair?
The format of the mysql_fetch_assoc should be
array('chat'=>'Some chat', 'time_sent'=>'123456', 'username'=>'abcdefg')
json_encode would directly translate this to
{"chat":"Some chat", "time_sent":"123456", "username":"abcdefg"}
So in your loop, if you simply do $mesages[] = $row; and leave your json_encode call as-is, it should work as shown above. However, you can alter your SQL statement to give the columns an alias so that time_sent simply shows as the property time
This is what i would do:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
$loopCount = count($chats);
if(count($messages) > 0){
echo json_encode($messages);
}
This will output if not encoded:
Array
(
[0] => Array
(
[chat] => chat_0
[time] => time_sent_0
[username] => username_0
)
[1] => Array
(
[chat] => chat_1
[time] => time_sent_1
[username] => username_1
)
[2] => Array
(
[chat] => chat_2
[time] => time_sent_2
[username] => username_2
)
[3] => Array
(
[chat] => chat_3
[time] => time_sent_3
[username] => username_3
)
)
And this if encoded:
[{"chat":"chat_0","time":"time_sent_0","username":"username_0"},
{"chat":"chat_1","time":"time_sent_1","username":"username_1"},
{"chat":"chat_2","time":"time_sent_2","username":"username_2"},
{"chat":"chat_3","time":"time_sent_3","username":"username_3"}]
To parse the JSON
lets say you have your JSON results in a data var
var obj = $.parseJSON(data);
$.each(obj, function(i, value){
console.log(value.chat);
});
You need to work with multi-dimensional arrays in order to get this to work. The code below has been edited to assign values to named indexes and append these to the 2nd level to the $messages array.
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = Array(
'chat' => $row['chat'],
'time' => $row['time_sent'],
'username' => $row['username']
);
}
The while cycle should be like this:
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
Save a little time by getting the field names correct within the SQL.
$SQL = sprintf('SELECT time_sent as `time`, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ($row = mysql_fetch_assoc($result)) {
$messages[] = $row;
}
echo json_encode($messages);
IMO returning an empty array when there are no messages is better than returning nothing, as now you have a way to differentiate if your php worked vs if you had no messages, from within your JavaScript code.

Categories

Resources