I have two arrays $pq and $rs. please see them below:
$pq = array ('page-0'=>array ('line-0'=>array('item-0'=>array('name'=>"item-00",'value'=>"123"),
'item-1'=>array('name'=>"item-01",'value'=>"456")
),
'line-1'=>array('item-0'=>array('name'=>"item-10",'value'=>"789"),
'item-1'=>array('name'=>"item-11",'value'=>"012")
)),
'page-1'=>array ('line-0'=>array('item-0'=>array('name'=>"item-100",'value'=>"345"),
'item-1'=>array('name'=>"item-101",'value'=>"678")
),
'line-1'=>array('item-0'=>array('name'=>"item-110",'value'=>"901"),
'item-1'=>array('name'=>"item-111",'value'=>"234")
),
'line-2'=>array('item-0'=>array('name'=>"item-210",'value'=>"567"),
'item-1'=>array('name'=>"item-211",'value'=>"890")
))
);
$rs = array ('1'=>array('name'=>'item-00', 'value'=>"abc"),
'2'=>array('name'=>'item-01', 'value'=>"def"),
'3'=>array('name'=>'item-10', 'value'=>"ghi"),
'4'=>array('name'=>'item-11', 'value'=>"jkl"),
'5'=>array('name'=>'item-100', 'value'=>"mno"),
'6'=>array('name'=>'item-101', 'value'=>"pqr"),
'7'=>array('name'=>'item-110', 'value'=>"stu"),
'8'=>array('name'=>'item-111', 'value'=>"vwx")
);
What I am trying to do is to replace the values in $pq for items with the values from $rs.
for example item-01 in $pa to be replaced with abc from $rs.
What I tried is this:
foreach($rs as &$rs1) {
echo "first count :".$firstCount."<br>";
foreach($pq as $pages) {
foreach($pages as $lines) {
foreach($lines as &$item) {
if ($item['name'] == $rs1['name']) { echo "matching </p>";
$item['value']=$rs1['value'];
echo '<pre>';
print_r($item);
echo '</pre>';
echo "<hr>";
}
}
}
}
}
When I print the values of $item from $pq, it prints the values from $rs, but when I print the whole array $pq, the values seem to be unchanged.
Can anyone please help me find out what I am missing ?
You're correctly looping through the items in each line by reference, but you're not doing it for the lines or pages themselves. So you're updating the value of an item in a copy of the line, instead of the line itself. It should be:
foreach($rs as $rs1) {
echo "first count :".$firstCount."<br>";
foreach($pq as &$pages) {
foreach($pages as &$lines) {
foreach($lines as &$item) {
if ($item['name'] == $rs1['name']) { echo "matching </p>";
$item['value']=$rs1['value'];
echo '<pre>';
print_r($item);
echo '</pre>';
echo "<hr>";
}
}
}
}
}
Note that the & in front of &$lines and &$pages. Note also that $rs1 doesn't need to be passed by reference, since you aren't changing anything in that array.
You’ve assigned $item by reference but haven’t done the same for $pages and $lines. There will be no effect on the actual values of $pq unless you assign $pages by reference; similarly, the actual values of $pages will remain unchanged unless you assign $lines by reference. Therefore, in order to achieve what you want, change foreach($pq as $pages) to foreach($pq as &$pages) and foreach($pages as $lines) to foreach($pages as &$lines).
You can build a search array first so that you can match items easier:
$search = array_reduce($rs, function(&$prev, $current) {
$prev[$current['name']] = $current;
return $prev;
}, []);
This creates another array with the item name as the key. Then, you iterate over each item in $pq and modify the leaves where necessary:
foreach ($pq as &$page_data) {
foreach ($page_data as &$line_data) {
foreach ($line_data as &$item_data) {
if (isset($search[$item_data['name']])) {
$item_data = $search[$item_data['name']];
}
}
}
}
Make sure to use references at each level of iteration.
Related
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
}
}
I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}
My Script :
<?php
$values='Product1,54,3,888888l,Product2,54,3,888888l,';
$exp_string=explode(",",$values);
$f=0;
foreach($exp_string as $exp_strings)
{
echo "".$f." - ".$exp_string[$f]." ";
if ($f%3==0)
{
print "<br><hr><br>";
}
$f++;
}
?>
With this code i want show data inside loop, the idea it´s show all information in groups the elements in each group it´s 4 elements and must show as this :
Results :
Group 1 :
Product1,54€,3,green
Group 2:
Product2,56€,12,red
The problem it´s i don´t know why, don´t show as i want, and for example show separate some elements and not in group, thank´s , regards
It looks like you are trying to combine elements of a for loop and a foreach loop.
Here is an example of each, pulled from the php manual:
For Loop
for($index = 0, $index < size($array), $index++ {
//Run Code
//retrieve elements from $array with $array[$index]
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
It's hard for me to understand what your input looks like. If you post an example of $exp_strings, I could be of better assistance. But from the sound of your question, if $exp_strings is multidimensional if you need to loop through groups of items, you could try nesting one loop inside another loop like so:
$groups_of_data = array(array(...), array(...), array(...));
for($i = 0, $i < size($groups_of_data), $i++) {
$group = $i;
for($j = 0, $j < size($groups_of_data[$i]), $j++) {
// print out data related to group $i
}
}
This is really all guesswork on my part though as I can't see what your input string/array is. Can you post that? Maybe I can be of more help.
here is code i worked out. it was kind of since i did't know what object $exp_string is. if it's a string you should tokenize it, but i think it's array from database. there was another problem, with your code where it tries to output $exp_string[$f] it should be $exp_strings what changes in the loop.
my code
$exp_string=array("Product"=>54,"price"=>3,"color"=>"green");
$f=0;
foreach($exp_string as $key => $exp_strings)
{
if($f%3==0)
{
print "<br><hr><br>";
echo "Product ".$exp_strings."<br> ";
}
else if($f%3==1)
{
echo "Price ".$exp_strings."<br> ";
}
else if($f%3==2)
{
echo "Color ".$exp_strings."<br> ";
}
$f++;
}
hope it's any help, maybe not what you wanted.
$values='Product1,1,2,3,Product2,1,2,3,Product3,1,2,3';
$products = (function($values) {
$exp_string = explode(',', $values);
$products = [];
for ($i=0; $i+3<count($exp_string); $i+=4) {
$product = [
'title' => $exp_string[$i],
'price' => $exp_string[$i+1],
'color' => $exp_string[$i+2],
'num' => $exp_string[$i+3],
];
array_push($products, $product);
}
return $products;
})($values);
/* var_dump($products); */
foreach($products as $product) {
echo "{$product['title']},{$product['price']},{$product['color']},{$product['num']}<br>";
}
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]);
}
I have a multidimensional array in PHP produced by the great examples of icio and ftrotter (I am use ftrotterrs array in arrays variant):
Turn database result into array
I have made this into a unordered list width this method:
public function outputCategories($categories, $startingLevel = 0)
{
echo "<ul>\n";
foreach ($categories as $key => $category)
{
if (count($category['children']) > 0)
{
echo "<li>{$category['menu_nl']}\n";
$this->outputCategories($category['children'], $link
, $start, $startingLevel+1);
echo "</li>\n";
}
else
{
echo "<li>{$category['menu_nl']}</li>\n";
}
}
echo "</ul>\n";
}
So far so good.
Now I want to use the url_nl field to build up the url's used as links in the menu. The url has to reflect the dept of the link in de tree by adding up /url_nl for every step it go's down in the tree.
My goal:
- item 1 (has link: /item_1)
* subitem 1 (has link: /item_1/subitem_1)
* subitem 2 (has link: /item_1/subitem_1)
* subsubitem 1 (has link: /item_1/subitem_2/subsubitem_1)
- item 2 (has link: /item_2)
the table
id
id1 (parent id)
menu_nl
url_nl
title_nl
etc
What I have so far:
public function outputCategories($categories, $link, $start, $startingLevel = 0)
{
// if start not exists
if(!$start)
$start = $startingLevel;
echo "<ul>\n";
foreach ($categories as $key => $category)
{
$link.= "/".$category['url_nl'];
if($start != $startingLevel)
$link = strrchr($link, '/');
if (count($category['children']) > 0)
{
echo "<li>".$start." - ".$startingLevel.
"<a href='$link'>{$category['menu_nl']}</a> ($link)\n";
$this->outputCategories($category['children'], $link
, $start, $startingLevel+1);
echo "</li>\n";
}
else
{
$start = $startingLevel+1;
echo "<li>".$start." - ".$startingLevel.
"<a href='$link'>{$category['menu_nl']}</a> ($link)</li>\n";
}
}
echo "</ul>\n";
}
As you see in the example I have used a url_nl field which is recursively added so every level of the list has a link with a path which is used as a url.
Anyhow, I have problems with building up these links, as they are not properly reset while looping to the hierarchical list. After going down to the child in de list the first one is right but the second one not.
I'm stuck here...
It looks like you modify the $link variable inside the foreach loop, So you add item1 to $link, loop thru its subitems and return to the first iteration and add item2 to the variable...
replace this
$link .= "/".$category['url_nl'];
with
$insidelink = $link . "/".$category['url_nl'];
(and change remaining $link inside the loop to $insidelink)
Adding: This is also true for $startingLevel. Do not modify it, use +1 inline:
echo "<li>".$start." - ".$startingLevel +1.
"<a href='$link'>{$category['menu_nl']}</a> ($link)</li>\n";
Here is an easier way:
$inarray = your multi-dimensional array here. I used directory_map in codeigniter to get contents of directory including it's subdirectories.
$this->getList($filelist2, $filelist);
foreach ($filelist as $key => $val) {
echo $val;
}
function getList($inarray, &$filelist, $prefix='') {
foreach ($inarray as $inkey => $inval) {
if (is_array($inval)) {
$filelist = $this->getList($inval, $filelist, $inkey);
} else {
if ($prefix)
$filelist[] = $prefix . '--' . $inval;
else
$filelist[] = $inval;
}
}
return $filelist;
}