foreach looping in multidimension array in php - loops

Here is my PHP code:
$marks = array(
'Mohammad' => array('Phisics' => 50, 'Math' => 80),
'Arif' => array('Phisics' => 55, 'Math' => 95),
);
Now I want to get the Mohammad and Arif's marks with subject using foreach loop.

You can use a nested foreach loop:
foreach ($marks as $name => $subjects) {
foreach ($subjects as $subjectName => $subjectMark) {
echo "${name}'s mark for ${subjectName} is ${subjectMark}.";
}
}

Try this
$marks = array(
'Mohammad' => array('Phisics' => 50, 'Math' => 80),
'Arif' => array('Phisics' => 55, 'Math' => 95),
);
foreach ($marks as $key=>$names) {
echo "--$key Marks-- <br/>";
foreach ($names as $key=>$value) {
echo "$key:$value <br/>";
}
}
Output
--Mohammad Marks--
Phisics:50
Math:80
--Arif Marks--
Phisics:55
Math:95

Related

Convert array laravel

I use Laravel framework and I have an array:
[▼
"0.022" => "24.00000000"
"0.013" => "506.00000000"
"0.041" => "65.00000000"
]
Could you help me to convert it to new format like this:
[▼
0 => {▼
"xxx": 0.022
"yyy": 24.00000000
}
1 => {▼
"xxx": 0.013
"yyy": 506.00000000
}
2 => {▼
"xxx": 0.041
"yyy": 65.00000000
}
]
Thank you very much.
$inputArray=array(
"0.022" => "24.00000000"
"0.013" => "506.00000000"
"0.041" => "65.00000000"
);
$outputArray=array();
foreach($inputArray as $key=>$val)
{
$obj['xxx']= $key;
$obj['yyy']= $val;
array_push($outputArray,$obj)
}
echo $outputArray;
$array = [
"0.022" => "24.00000000",
"0.013" => "506.00000000",
"0.041" => "65.00000000"
];
$data=array();
foreach($array as $key=>$value)
{
$data[]= ['xxx'=>$key,'yyy'=>$value];
}
echo "<pre>";
echo(json_encode($data));
Based on your output, you want increment index as the key
$item = [
'0.022' => '24.00000000',
'0.013' => '506.00000000',
'0.041' => '65.00000000'
];
$output = [];
$count = 0;
foreach($item as $key => $value) {
$output[$count]['xxx'] = $key;
$output[$count]['yyy'] = $value;
$count++;
}
echo json_encode($output);

Why can I not achieve the same result with Collection::reduce() as with foreach?

I'm having trouble wrapping my head around CakePHP's Collection::reduce. Actually, it feels like I understand how it's supposed to work, but in reality it seems to work differently. I have a collection of entities, from which I'm trying to concat a number of strings, based on the contents of another array. The array has an ID, the collection has that ID as a sort of foreign ID. I loop through the array, and then in each loop I loop through the collection to find the entities which have a foreign ID matching the ID from the array. Implementing this with Collection::reduce gives a wildly different result from doing it with two foreach() loops. Anyway, here's the code:
public function reducetest() {
$this->render('test');
$groupby = ['a' => 1, 'b' => 2];
$array = [
array('id' => 'b', 'title' => 'array_tag_1'),
array('id' => 'a', 'title' => 'array_tag_2'),
array('id' => 'b', 'title' => 'array_tag_3'),
array('id' => 'a', 'title' => 'array_tag_4'),
array('id' => 'a', 'title' => 'array_tag_5')
];
$array_result = array();
foreach ($groupby as $key => $value) {
$array_result[$key] = '';
foreach ($array as $item) {
if ($key === $item['id']) {
// debug($array_result[$key] . $item['title'] . ", \n");
$array_result[$key] .= $item['title'] . ', ';
}
}
$array_result[$key] = trim($array_result[$key], ', ');
}
debug($array_result);
$collection = new Collection([
array('id' => 'b', 'title' => 'collection_tag_1'),
array('id' => 'a', 'title' => 'collection_tag_2'),
array('id' => 'b', 'title' => 'collection_tag_3'),
array('id' => 'a', 'title' => 'collection_tag_4'),
array('id' => 'a', 'title' => 'collection_tag_5')]
);
$collection_result = array();
foreach ($groupby as $key => $value) {
$collection_result[$key] = $collection->reduce(function ($string, $item) use ($key) {
if ($key === $item['id']) {
// debug($string . $item['title'] . ", \n");
return $string . $item['title'] . ', ';
}
}, '');
$collection_result[$key] = trim($collection_result[$key], ', ');
}
debug($collection_result);
}
The code with the two foreach() loops produces this result, as expected:
[
'a' => 'array_tag_2, array_tag_4, array_tag_5',
'b' => 'array_tag_1, array_tag_3'
]
The code that uses the reduce function gives this result - which is incomprehensible, to me:
[
'a' => 'collection_tag_4, collection_tag_5',
'b' => ''
]
Can you explain to me what I'm not getting here?

get the images attached to a post but not the featured image in wordpress

$attachments = array(
'post_type' => 'portfolio',
'order' => 'ASC',
'posts_per_page' => '-1'
// 'exclude' => get_post_thumbnail_id()
);
$main_qury = new WP_Query($attachments);
$mate=$main_qury->posts;
foreach ( $mate as $attachment ) {
// $class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_image_src( $attachment->ID, 'thumbnail-size', true );
// echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
echo "<pre>";
print_r($thumbimg);
}
i want to get only those images who are not featured but now i m getting image with post content...how can i separate post content with an image...
I have no idea why you're attempting to use a WP_Query like that.
Try this instead:
global $post;
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id(),
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo wp_get_attachment_image( $attachment->ID, 'large' );
}
}
Replace large in wp_get_attachment_image() with whatever size you want to use.

Wordpress Sum meta_values from posts and order them per category

I'm using this code to query all the categories from an array and sum the meta_key values per category:
<?
$arr_cat = array(1,34,64,32);
foreach ($arr_cat as $cat) {
$MySum = 0;
$args = array(
'cat' => $cat,
'meta_key' => 'proyecto_votos',
'post_type' => 'proyecto',
'posts_per_page' => '-1');
$the_query = new WP_Query( $args);
while ( $the_query->have_posts() ) : $the_query->the_post();
$MySum += get_post_meta($post->ID, 'proyecto_votos', true);
endwhile;
wp_reset_postdata();
}
//var_dump($arr_cat);
?>
And it works ok. But I can't show only the top 5 categories with most sum of custom_value. Please can you help me out on this.
Thanks so much.
Only for top 5 posts
$args = array(
'cat' => $cat,
'post_type' => 'proyecto',
'meta_key' => 'proyecto_votos',
'orderby'='meta_value_num',
'posts_per_page' => '5' // top 5 posts using ASC order by default
);
posts_per_page => -1 will show all posts.
Reference.
Finally with a little bit of google i got it :-):
<? $totalvotes = get_meta_values( 'proyecto_votos', 'proyecto' ); ?>
<?
foreach ($arr_cat_reg as $cat) {
$MySum = 0;
$args = array(
'cat' => $cat,
'meta_key' => 'proyecto_votos',
'post_type' => 'proyecto',
'posts_per_page' => '-1' );
$the_query = new WP_Query( $args);
while ( $the_query->have_posts() ) : $the_query->the_post();
$MySum += get_post_meta($post->ID, 'proyecto_votos', true);
endwhile;
//echo $MySum.'<br/>';
$percent = $MySum * 100;
$percent = $percent / $totalvotes;
//echo $percent;
wp_reset_postdata();
$catslug = get_cat_slug($cat);
$most_voted[] = array('region' => $catslug, 'votos' => $MySum);
}
$sortArray = array();
foreach($most_voted as $region){
foreach($region as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "votos";
array_multisort($sortArray[$orderby],SORT_DESC,$most_voted);
$top5 = array_slice($most_voted, 0, 5);
?>
I Hope this helps somebody.

PHP: Foreach echo not showing anything

EDIT
Now I can output the current product, but every time the form adds another item it gets overriden. I want to make the list incremental like this:
1. Banana 3 Units, Price 350 CRC
2. Yougurt 4 Units Price 2000 CRC
3. etc etc
4. etc
The current output only shows the last added item.
This is the script:
<?php
session_start();
//Getting the list
$list= $_SESSION['list'];
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$_SESSION['list'] = array(
'item' => ($_POST['product']),
'quantity' => ($_POST['quantity']),
'code' => ($_POST['code']),
);
//price
$price = $products[($_SESSION['list']['item'])] * $_SESSION['list']['quantity'];
$_SESSION['list']['price'] = $price;
//listing
echo "<b>SHOPPIGN LIST</b></br>";
foreach($_SESSION as $key => $item)
{
echo $key[''], '. ', $item['item'], ' ', $item['quantity'], ' units: ', $item['price'];
}
//Recycling list
$_SESSION['list'] = $list;
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
var_dump($_SESSION);
?>
This line is your issue.
$_SESSION['list'] = array('price' => $price,);
You're setting the variable you're trying to iterate across to be an array with a single entry in it, not to mention the fact that $price isn't going to be a nested array, which is why trying to get item['key'] is failing (as in 'price' will be your key and $price will be your item in your foreach).
EDIT:
I believe, from a second quick glance you're actually intending to do this:
$_SESSION['list']['price'] = $price;
correct me if I'm wrong.
EDIT 2:
Actually, looking again, I'm not quite sure I understand your structure for your $_SESSION['list'] variable. It looks like you want something like:
(('item' => 'Banana', 'quantity' => 1...), ('item' => 'Apple', 'quantity' => 2...))
but what you have (from the fact you reference $_SESSION['list']['item']) is only:
('item' => 'Banana', 'quantity' => 1...)
you actually have multiple problems here. First try and deal with the bad structure of $_SESSION['list'] then try and deal with the foreach loop.
EDIT 3:
I still don't think you're quite understanding what I mean, so I'm just going to fix the code to be what I'm pretty sure you're looking for...
I'm pretty sure what you're going for looks something like this:
<?php
session_start();
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
if(!array_key_exists('list', $_SESSION)){
$_SESSION['list'] = array();
}
$price = $products[$_POST['product']] * $_POST['quantity'];
array_push($_SESSION['list'],
array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $price,
));
echo "<b>SHOPPING LIST</b></br>";
foreach($_SESSION['list'] as $key => $item) {
echo $key+1, '. ', $item['item'], ' ', $item['quantity'], ' units: ', $item['price'];
}
echo "</br> <a href='index.html'>Return to index</a> </br>";
?>
You're overriding your $_SESSION['list'] value with just the calculated price, so when you iterate through $_SESSION['list'], the only thing you have in $item is a scalar value of the calculated subtotal, not the array you hope for under your 'saving the stuff' comment.
If you're simply trying to print out the array of product/quantity/code/price this should work:
<?php
session_start() ;
//Stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
$_POST['product'] = 'Banana' ;
$_POST['quantity'] = 50 ;
$_POST['code'] = "unknown" ;
//Saving the stuff
$_SESSION['list'] = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
print_r($_SESSION['list']) ;
//listing
echo "<b>SHOPPING LIST</b></br>\n";
foreach($_SESSION as $key => $item) {
echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units ', $item['price']."\n";
}
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Recycling list
$_SESSION['list'] = '';
//Printing session
print_r($_SESSION);
?>
That will print this result:
list. Banana 50 units 2500

Resources