modify key in a foreach loop php - 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]);
}

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)
}
}

Filter JSON array with objects inside in PHP

I have a particular JSON file that looks like this:
[
{
"objID":"kc6BvvNlVW",
"string":"bill",
"createdOn":"2018-09-18T01:51:02",
"updatedOn":"2018-09-18T01:51:02",
"number":1,
"boolean":true,
"array":["item1","item2"],
"pointer":{"type":"__pointer","objID":"hYtr54Ds","className":"Users"}
},
{
"objID":"sS1IwFPPWh",
"string":"tom",
"createdOn":"2018-09-18T01:59:40",
"updatedOn":"2018-09-18T01:59:40",
"number":12.3,
"boolean":false,
"array":["item1","item2"],
"pointer":{"type":"__pointer","objID":"tRe4Fda5","className":"Users"}
}
]
1. I need to first check if the "pointer" object has "__pointer" inside the type key and show only the objID value in an HTML table, like this:
"tRe4Fda5"
Right now, this is how my table looks like:
And here's my foreach PHP code (into a table row):
foreach($jsonObjs as $i=>$obj) {
$row_id = $i;
echo '<tr>';
foreach($obj as $key => $value){
// $value is an Array:
if (is_array($value)) {
echo '<td>';
foreach($value as $k=>$v){
// $v is a Pointer
if ($v === '__pointer') {
echo json_encode($v); // <-- WHAT SHOULD I DO HERE ?
// $v is an Array:
} else {
echo json_encode($v);
}
}
echo '</td>';
// $value is a Number:
} else if (is_numeric($value)){
echo '<td>'.(float)$value.'</td>';
// $value is a String:
} else { echo '<td>'.$value.'</td>'; }
}
As you can see in the pointer column, the string I get is:
"__pointer""hYtr54Ds""Users"
with no commas as separators, so this is the line of code I need to edit:
echo json_encode($v); // <-- WHAT SHOULD I DO HERE ?
I've tried with echo json_encode($v[$k]['__ponter']);, but no positive results.
So my final first question is: how can I get each VALUE of the "pointer" array?
2. Also, the second row of the boolean column shows noting since its value is false, shouldn't it show 0, since the first row shows 1 (true)?
You can look into the object during the second loop to see if it has a property called type and if that property is set to __pointer.
foreach($jsonObjs as $i=>$obj) {
$row_id = $i;
foreach($obj as $key => $value){
// see if $value has a type property that is set to pointer
if (isset($value['type']) && $value['type'] == "__pointer") {
// $value is the pointer object. Do with it what you will
echo "<td>" . $value['objID'] . "</td>";
}
// more code
}
}
instead of
foreach($value as $k=>$v){
// $v is a Pointer
use
foreach($value as $k)
{
//then check for pointer
if($k->type === '__pointer')
{
echo json_decode($k); //here you will get proper key and value
}
}

Get JSON Array With 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;
}
}

Echo out key and value from array

I have an array called $topProductIdResults and it looks like the following:
Array ( [11497522] => 2 )
The keys are prodcuct ID's and the value is the number of 5 star ratings that the product has recieved.
I want it to echo out this data using a loop. However I can't work our how to echo out both the key and value. Sometimes there will be several product ID's and number pairs in this array. Please let me know where I'm going wrong. My code so far is:
foreach ($topProductIdResults as $prod) {
echo $prod[0];
echo $prod[1];
}
which just echo's 22 at the moment. I want it to echo 11497522 2
foreach ($topProductIdResults as $key => $value) {
echo $key;
echo $value;
}
Try this :
foreach ($topProductIdResults as $key=>$prod) {
echo $key;
echo $prod;
}
Ref: http://php.net/manual/en/control-structures.foreach.php
If you just have a single dimensional array with key and value Array ( [11497522] => 2 ) , then you can use this :
$array = array(11497522=>2);
$key = key($array);
$value = $array[$key];
Use this
foreach ($topProductIdResults as $key => $value)
{
echo $key;
echo $value;
}
Try this
foreach ($topProductIdResults as $prodid => $prod) {
echo $prod[0];
echo $prod[1];
}

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 ...)

Categories