php foreach loop show duplicate item - php

I have a foreach loop and have a problem with it. My loop show duplicate some item and I want show item only once and don't duplicate item. My loop it is.
foreach($result as $res){
$id = $res->id;
$title = $res->title;
echo $title;
}

$partial=array();
foreach($result as $res){
if (!in_array($res->id, $partial)) {
$id = $res->id;
$title = $res->title;
echo $title;
array_push($partial, $res->id);
}
}

try this one..
$present_array = array();
foreach($result as $res){
if(!in_array($res->title, $present_array)){
$present_array[] = $res->title;
$id = $res->id;
$title = $res->title;
echo $title;
}
}

<?php
function remove_dup($matriz) {
$aux_ini=array();
$entrega=array();
for($n=0;$n<count($matriz);$n++)
{
$aux_ini[]=serialize($matriz[$n]);
}
$mat=array_unique($aux_ini);
for($n=0;$n<count($matriz);$n++)
{
$entrega[]=unserialize($mat[$n]);
}
return $entrega;
}
foreach(remove_dup($result) as $res){
$id = $res->id;
$title = $res->title;
echo $title;
}
another solution is, if you are getting this data from database then use DISTINCT in your select query.

Do a fast check & make your code execute faster like this:
$check_dup = array();
foreach ($items as $item){
if (in_array($item['id'], $check_dup))
continue;
else {
array_push($check_dup, $item['sid']);
/* your code in foreach loop */
}
}

Try this:
$result = array(
array(
'id' => "1",
'title' => "My title"
),
array(
'id' => "2",
'title' => "My title 2"
)
);
foreach($result as $res){
$id = $res['id'];
$title = $res['title'];
echo $title . "<br>";
}

Related

echo out $_SESSION data

I have a bunch of data in an array which has been collected in a session. I am able to print_r this and show all the contents but I am struggling to show the product name, id, image etc.
I am showing the using:
<?php
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>
It prints out everything I need but not in the format I require. So I know it is collecting my data and storing it in the array. I have set the data in another files like so:
if (isset($_POST['Submit'])) {
$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description'];
}
And it is all of the above I want to output.
**Either you stick with your proposal : $_SESSION['...'][] **
if (isset($_POST['Submit'])) {
$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description'];
}
and format it like so:
foreach($_SESSION as $elements)
{
foreach($elements as $element) {
echo $element . '<br />';
}
}
Or use this other method:
if (isset($_POST['Submit'])) {
$_SESSION['product_img'] = $_POST['product_img'];
$_SESSION['product_id'] = $_POST['product_id'];
$_SESSION['product_name'] = $_POST['product_name'];
$_SESSION['product_price'] = $_POST['product_price'];
$_SESSION['product_sku'] = $_POST['product_sku'];
$_SESSION['product_description'] = $_POST['product_description'];
}
and format it like so:
foreach($_SESSION as $element)
{
echo $element . '<br />';
}
A simple way to output this as HTML is to use a foreach loop, which goes through each item in the array.
To make things easier, I would suggest changing your POST code so that each item is a single array, like so.
if (isset($_POST['Submit'])) {
$_SESSION['products'][] = array(
'img' => $_POST['product_img'],
'id' => $_POST['product_id'],
'name' => $_POST['product_name'],
'price' => $_POST['product_price'],
'sku' => $_POST['product_sku'],
'description' => $_POST['product_description']
);
}
Now you can iterate through $_SESSION['products'] and get the information for each product in the session. For example:
foreach ($_SESSION['products'] as $product) {
$name = $product['name'];
$id = $product['id'];
$price = $product['price'];
$img = $product['img'];
$sku = $product['sku'];
$description = $product['description'];
echo "<h1>Product: $name</h1>";
echo "<p>Price: $price | ID: $id</p>";
echo "<img src='$img'>";
echo "<p>$description</p>";
echo "<hr />";
}

array result using foreach statement display in json in php

I am getting the result from web service SOAP client. I have created an array to get the result and display it using json format. I am getting few of my results properly. I have SerialEquipment parameter which is array and i need to get the result using foreach loop. I am doing an mistake there. I dont know how can i assign my $vehiclResult array in this for each statement. So that all the results at last i will collect and display using json using vehicleResult array.My mistake is in the foreach loop.
structure for SerialEquipment parameters:
Code:
$vehicle = getVehicleValuation();
$Serial=$vehicle['SerialEquipment'];
$vehiclResult = array(
'WE_Number' => $vehicle['WE Number'] ."<br>",
'Vehicle Type'=> $vehicle['Vehicle Type'] . "<br>",
'HSN' => $vehicle['HSN'] . "<br>",
'TSN' => $vehicle['TSN'] . "<br>"
);
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['SerialEquipment'] = $key. "<br>";
$vehiclResult[$key]['Code'] = $obj->Code. "<br>";
$vehiclResult[$key]['Desc Short'] = $obj->Desc_Short. "<br>";
$vehiclResult[$key]['Desc Long'] = $obj->Desc_Long. "<br>";
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc). "<br>";
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc). "<br>";
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
}
You need to check if your array have the key so:
if(!isset($vehiclResult[$key]))
if not, you need to create it:
$vehiclResult[$key] = array(); // as an array
Also, you don't really need to make a description of your "item". You can Parse your JSON on the result page to output some text.
You can do something like.
Do something like:
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['serial'] = $key;
$vehiclResult[$key]['code'] = $obj->Code;
$vehiclResult[$key]['short_desc'] = $obj->Desc_Short;
$vehiclResult[$key]['long_desc'] = $obj->Desc_Long;
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2;
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode;
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc;
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode;
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc);
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode;
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc);
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
If you would keep your "text" and your <br> code, do the samething but add what you want to output after the "="
EDIT
** A HAVE CHANGE THE CODE PREVIOUSLY..
if you want to test your $vehiclResult, try something like:
foreach($vehiclResult as $key=>$value){
if(!is_array($value))
var_dump($value);
else {
foreach($value as $key2=>$value2){
if(!is_array($value2))
var_dump($value2);
else {
foreach($value2 as $key3=>$value3){
var_dump($value3);
}
}
}
}

My array returns array inside foreach

could someone explain me why I can not get the data from that array?
My echo only returns "array". where I'm going wrong?
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));
foreach($people as $vperson => $person){
echo $person;
}
?>
Well as you said you have an array, your variable $person is also an array so you can't just make echo on that. You can access values by the names "age, name and colour".
Try this:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));
foreach($people as $vperson => $person){
echo $name = $person['name'];
echo $age = $person['age'];
echo $colour = $person['colour'];
echo "<br>";
}
?>
Because, your are printing array with echo.
You can print the array like:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));
foreach($people as $vperson => $person){
echo '<pre>';
print_r($person);
echo '</pre>';
echo $name = $person['name'];
echo $age = $person['age'];
echo $colour = $person['colour'];
}
Use this to display key and equivalent value
foreach($people as $pe)
{
foreach($pe as $key => $person)
{
echo $key.' : '.$person.' </br> ';
}
}

how to update mysql table from Serialised json?

I have get Serialised from Nestable, but I don't know how to write php code update my database like wordpress:
$data = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
function extract_value($value,$order=0){
if(is_array($value)){
foreach($value as $k => $v){
echo "UPDATE vod_page_menu SET ordering = '$order', parent_id = '$v' WHERE id = '$v'; <br/>";
extract_value($v,$order+1);
}
}
}
$json = json_decode($data,true);
extract_value($json);
You need to first decode the JSON, then you can use it in PHP:
$data = json_decode($data, true);
foreach ($data as $id => $value) {
...
}
function extract_value($array,$parent=0,$i=1){
foreach($array as $k => $v) {
$id = $array[$k]['id'];
echo "UPDATE vod_page_menu SET ordering = '$i', parent_id = '$parent' WHERE id = '$id'; <br/>";
if(isset($array[$k]['children'])){
$children = $array[$k]['children'];
foreach($children as $key => $obj){
$child = $children[$key]['id'];
$i++;
echo "UPDATE vod_page_menu SET ordering = '$i', parent_id = '$id' WHERE id = '$child'; <br/>";
if(isset($children[$key]['children']))
extract_value($children[$key]['children'],$child,++$i);
}
}
$i++;
}
}

Organizing results by category Redux

I am trying to expand on my question asked here: Creating a multi-dimensional array from query
I have added a category description to my categories table but I cannot figure out how to add it to the code below and display each category description for each category.
Here is the code I am using to display the items by category:
$itemcategories = array();
while ($row = mysqli_fetch_array($result))
{
$head = $row['category'];
$itemcategories[$head][] = array(
'id' => $row['id'],
'title' => $row['title'],
'itemdesc' => $row['itemdesc'],
'price' => $row['price'],
'special' => $row['special']
);
}
<?php foreach ($itemcategories as $head => $items) { ?>
<h3><?php echo $head; ?></h3>
<table class="chart">
<?php foreach ($items as $item) { ?>
<tr><td><?php echo $item['itemdesc']; ?></td></tr>
<?php } ?>
</table>
<?php } ?>
// to initial variable holder
$categories = $items = array();
// looping mysql result
while ($row = mysqli_fetch_array($result))
{
// to get category name
$head = $row['category'];
// avoid excessive setting of $categories
if (!isset($categories[$head]))
{
$categories[$head] = $row['descrption'];
}
// assign mysql result to $items
$items[$head][] = $row;
}
// free mysql result
mysql_free_result($result);
// loop all $categories
foreach ($categories as $head=>$desc)
{
// this is my example for printing HTML
// you can use heredoc syntax
// or stick to your existing format
echo "<h3>{$head} - {$desc}</h3><table class="chart">";
foreach ($items[$head] as $item)
{
// print item description
echo "<tr><td>{$item['itemdesc']}</td></tr>";
}
echo "</table>";
}

Categories