Get JSON Array With PHP - php

I have the following JSON string, I'm wanting to cycle through the 'sub' items and print them out as HTML Select Options but for some reason I can't quite get hold of them.
Only used JSON a couple times before so it's probably a rookie mistake somewhere.
{
"1":{
"question":"How happy are you with your car?",
"sub":[
"Very Happy",
"Not So Happy",
"Unhappy",
"Very Unhappy"
]
}
}
I have the following which let's me echo out the Question Value but how would I loop through each of the 'sub' arrays? (There's only ever going to be 1 question which is why I'm storing it in a single variable)
$questionAnswer = json_decode($data->question,true);
foreach ($questionAnswer as $key => $value) {
$question = $value['question'];
}

Add another loop inside the existing one:
$questionAnswer = json_decode($data->question,true);
foreach ($questionAnswer as $key => $value) {
$question = $value['question'];
echo $question."<br>";
// value['sub'] contains the array of 'subs', so you can loop through that the same way
foreach ($value['sub'] as $sub) { // since the key will be 0,1,2 you might not need it here, so I omitted it.
echo $sub."<br>";
}
}

foreach ($questionAnswer as $key => $value) {
$question = $value['question'];
foreach ($value['sub'] as $answer) {
echo $answer;
}
}

Related

foreach leaves out the very first value

I am processing a foreach(first) which gives the full array in the data, when I make another foreach(second) and pass the first foreach into second foreach the first value of the first foreach never appears in the second foreach. Does anyone have any idea why the foreach behaves this way? is there a solution for this?
I tried it this way no luck
$userIdsPerRoom = chatRoomUsersId($_SESSION['currentRoomID']);
foreach ($userIdsPerRoom as $value) {
$list[] =$value['UserID'];
}
foreach ($list as $value) {
$userInfo = chatRoomUsersEmail($value);
foreach ($userInfo as $info) {
echo $info['userEmail'];
}
}
echo count($list); ///gives the full list
}
I noticed it with this code
$userIdsPerRoom = chatRoomUsersId($_SESSION['currentRoomID']); //return an array of intergers with five values example array(1,2,3,4,5)
foreach ($userIdsPerRoom as $value){
$userInfo = chatRoomUsersEmail($value['UserID']);
foreach ($userInfo as $info){
echo $info['userEmail']; /// I only get four values example array(b,c,d,e)
}
}

How to access associate array of array in php?

I'm from Perl but I'm beginner in PHP. I'm having following array
$rating_data = Array ("51" => Array (5,3,4,2));
I'm trying to access the each data using loop so I tried following
foreach ($keys as $rating_data)
{
foreach ($index as $rating_data[$keys])
{
echo "$index";
}
}
But the above one is not working. I have also tried the below one also,
$all_keys = array_keys($rating_data);
foreach ($keys as $all_keys)
{
foreach ($values as $all_keys)
{
echo "$values";
}
}
But I didn't get the output. It works if I hard code the keys like below:
$rating_data["51"][0];
How to fix this issue.?
You can get the key position and iter value ( sencod level ).
foreach($rating_data as $key => $values)
{
echo $key; // Output "51"
foreach($values as $value)
{
echo $value; // Output: iter1: "5", iter2: "3", iter3: "4", iter1: "2",
}
}
It should be as simple as below:
foreach($rating_data as $key => $values) {
echo $key;
foreach($values as $value) {
echo $value;
}
}
You seem to have your parameters the wrong way around in your foreach statements. I would advise a quick read through the foreach docs.

modify key in a foreach loop php

I want to change the value of the $key because I have array_splice inside the loop which change the position of my values so - it mess up the value I need in a specific place.
I tried $key-- but it doesn't work.
for example when I print the $key after I do echo $key it's fine but when I echo $key just after the foreach loop I get the worng value.
Any ideas?
foreach ($cut as $key => $value) {
echo "foreach key:".$key."<br>";
if(in_array($value,$operators))
{
if($value == '||')
{
echo "found || in position:".$key."<br>";
if(($key+1<sizeof($cut)))
{
$multi = new multi;
echo "<br>"."key-1: ";
print_r($cut[$key-1]);
echo"<br>";
echo "<br>"."key+1: ";
print_r($cut[$key+1]);
echo"<br>";
$res = $multi->orex($cut[$key-1],$cut[$key+1],$numString);
$cut[$key-1]= $res;
array_splice($cut,$key,1);
array_splice($cut,$key,1);
$key--; //here trying to change the key
echo "new string:";
print_r($cut);
echo "<br>";
echo "key:".$key."<br>";
}
}
}
}
Updated
I don't think it is a good idea to change the array itself inside the foreach loop. So please crete another array and fill data into it, which will be your result array. This method works well when your array data is not big, in other words, most situations.
Origin
I don't know what do you mean. Let me give it a guess...
You want:
foreach($arr as $key=>$val){
$newkey = /* what new key do you want? */
$arr[$newkey] = $arr[$key];
unset($arr[$key]);
}

PHP Nested loops where values are the key to the next level of the array

I'm relatively new to PHP and I hope you can help me solve my problem. I am selecting out data from a database into an array for timekeeping. Ultimately, I would like to calculate the total number of hours spent on a project for a given customer.
Here is the code to populate a multi-dimensional array:
...
foreach ($record as $data) {
$mArray = array();
$name = $data['user'];
$customer = $data['customer'];
$project = $data['project'];
$hours = $data['hours'];
$mArray[$name][$customer][$project] += $hours;
}
...
I would now like to iterate over $mArray to generate an xml file like this:
...
foreach ($mArray as $username) {
foreach ($mArray[$username] as $customerName) {
foreach ($mArray[$username][$customerName] as $project ) {
echo '<'.$username.'><'.$customerName.'><'.$project.'><hours>'.
$mArray[$username][$customerName][$project].'</hours></'.$project.'>
</'.$customerName.'></'.$username.'>';
}
}
}
This nested foreach doesn't work. Can someone give me a couple of tips on how to traverse this structure? Thank you for reading!
UPDATE:
Based on the comments I've received so far (and THANK YOU TO ALL), I have:
foreach ($mArray as $userKey => $username) {
foreach ($mArray[$userKey] as $customerKey => $customerName) {
foreach ($mArray[$userKey][$customerKey] as $projectKey => $projectName) {
echo '<name>'.$userKey.'</name>';
echo "\n";
echo '<customerName>'.$customerKey.'</customerName>';
echo "\n";
echo '<projectName>'.$projectKey.'</projectName>';
echo "\n";
echo '<hours>'.$mArray[$userKey][$customerKey][$projectKey].'</hours>';
echo "\n";
}
}
}
This is now only providing a single iteration (one row of data).
Foreach syntax is foreach($array as $value). You're trying to use those values as array keys, but they're not values - they're the child arrays. What you want is either:
foreach($mArray as $username) {
foreach($username as ...)
or
foreach($mArray as $key => $user) {
foreach($mArray[$key] as ...)

Anything to attend when changing values in a multidimensional foreach() loop?

I got a site that executes the following code
$keywords = ($_SESSION[$_POST['ts']]);
print_r($keywords);
foreach ($keywords as $keyword) {
foreach ($keyword['whitelist'] as $entry) {
foreach ($_POST as $key => $value) {
if ($key == $entry['encoded_url']) {
$entry['ignore'] = $value;
$decodedURL = $this->base64->url_decode($entry['encoded_url']);
if ($value == 'noignore') {
echo "found!<br />";
$this->blacklist_model->remove($decodedURL);
$html = $this->analyse->getHTML($decodedURL);
$entry['html'] = $html[0];
$entry['loading_time'] = $html[1];
}
if($value == 'alwaysignore') {
$this->blacklist_model->add($decodedURL);
}
}
}
}
}
print_r($keywords);
The output looks like this:
http://pastebin.com/B3PtrqjB
So, as you see, there are several "found!"s in the output, so the if clause actually gets executed a few times and I expected the second array to contain new data like 'html', but, as you see, nothing changes. Is there anything to attend when changing values in multidimensional foreach() loops?
foreach creates a copy of the array and loops through that. Modifying values doesn't work.
You can get around this, though, by using references.
foreach ($keywords as &$keyword) {
foreach ($keyword['whitelist'] as &$entry) {
foreach ($_POST as $key => &$value) {
...
}
}
}
With that you can modify $value and it WILL affect the original array.
You suppose to change the Original array.
$entry is just an instance / unconnected node.
you need to change $keywords, and not its on the fly created nodes.

Categories