Output array information with PHP - php

I have the following array:
$features = array(
array(
'name' => 'Communication',
'plans' => array(
'standard' => 'yes',
'advanced' => 'yes'
)
),
array(
'name' => 'French',
'plans' => array(
'standard' => 'no',
'advanced' => 'yes'
)
)
);
How can I output this:
- Communication : standard > yes
- Communication : advanced > yes
- French : standard > no
- French : advanced > yes
What I tried:
foreach ($features as $feature => $info) {
echo $feature['name'].' : ' ['plans']['standard'].' > '.$feature['name']['plans']['standard'].'<br />';
echo $feature['name'].' : ' ['plans']['standard'].' > '.$feature['name']['plans']['advanced'].'<br />';
}
But it doesn't work because nothing is outputted.
Could you please help me ?
Thanks.

You should use a nested for loop as plans itself is an array as follows
foreach ($features as $feature) {
foreach($feature['plans'] as $key=>$val){
echo $feature['name'].' : '. $key.' > '.$val.'<br />';
}
}
I got the following output
Communication : standard > yes
Communication : advanced > yes
French : standard > no
French : advanced > yes

Try this:
foreach ($features as $feature => $info) {
echo $info['name'].' : standard > ' . $info['plans']['standard'].'<br />';
echo $info['name'].' : advanced > ' . $info['plans']['advanced'].'<br />';
}
You are referring to the wrong variable in your loop

This should do the trick. You should used $info to access the data inside because everytime you do a foreach loop, you get inside the parent array.
$features = array(
array(
'name' => 'Communication',
'plans' => array(
'standard' => 'yes',
'advanced' => 'yes'
)
),
array(
'name' => 'French',
'plans' => array(
'standard' => 'no',
'advanced' => 'yes'
)
)
);
foreach ($features as $feature => $info) {
echo $info['name']. ' : standard > '. $info['plans']['standard'] . '<br />';
echo $info['name']. ' : advanced > '. $info['plans']['advanced'] . '<br />';
}

Related

Loop in a multidimensional array and its subarray with PHP

I've the following array:
$items = array(
array(
'name' => 'Item 1',
'desc' => 'Lorem ipsum...',
'rates' => array(
'Yes' => 50,
'No' => 75
)
),
array(
'name' => 'Item 2',
'desc' => 'Lorem ipsum...',
'rates' => array(
'Yes' => 50,
'No' => 0
)
)
);
How can I loop between the rates ?
Here what I tried:
foreach ($items as $item) {
foreach($item['rates'] as $rate => $value){
echo $rate['rates'];
}
}
Thanks.
change your code to
foreach ($items as $item) {
foreach($item['rates'] as $rate => $value){
echo $value;echo '<br/>';
}
}
in second loop $rate is key and $value have the current value of that key.
To keep (and continue) your work:
foreach ($items as $item) {
echo "Number of ratings for item: {$item['name']}<br/>";
foreach($item['rates'] as $rateKey => $rateValue) {
echo " - {$rateKey}: {$rateValue}<br/>";
}
}
Output:
Number of ratings for item: Item 1
- Yes: 50
- No: 75
Number of ratings for item: Item 2
- Yes: 50
- No: 0
foreach ($items as $item) {
foreach($item['rates'] as $rate => $value){
echo 'Rate is ' . $rate . '; value is ' . $value . '<br />';
}
}
Loop within loop is way slower than looping and it would only become noticeable when array that you're looping gets bigger. So one approach you could take is given below:
$items = array(
array(
'name' => 'Item 1',
'desc' => 'Lorem ipsum text',
'rates' => array(
'Yes' => 50,
'No' => 75
)
),
array(
'name' => 'Item 2',
'desc' => 'Lorem ipsum text',
'rates' => array(
'Yes' => 50,
'No' => 0
)
)
);
$rates = array_column($items, 'rates');
foreach($rates as $key => $value) {
if($value['Yes']) {
echo " Yes: {$value['Yes']}<br/>";
}
echo " No: {$value['No']}<br/><br/>";
}
Result:
Yes: 50
No: 75
Yes: 50
No: 0

PHP: How do I compare values in nested associative arrays?

I'm trying to wrap my head around how to accomplish this…
I have an that's something like:
$contributors = array(
[0] => array(
[name] => 'John',
[role] => 'author',
),
[1] => array(
[name] => 'Gail',
[role] => 'author',
),
[2] => array(
[name] => 'Beth',
[role] => 'illustrator',
),
)
I'm trying to use this information to construct a detailed byline, like:
Written by John and Gail. Designed by Beth.
I need to compare each role to the previous and next ones in order to:
Use a label before the first instance of each role
Separate multiple instances of the same role with a comma
Use "and" instead of a comma before the last instance of each role
I'm no PHP expert so I'm having a hard time figuring out how to approach this! I have a function to output the right label depending on the role, but it's the comparisons I can't seem to figure out. I've considered foreach and while loops, but neither seems up to the job. I've never used a for loop so I don't know if it applies.
Some additional background:
I'm working with WordPress and the Advanced Custom Fields plugin.
$contributors is the value of an ACF Repeater field, where name and role are subfields. (I've simplified the names to make things easier.)
You can group the array per role and use array_pop to remove the element. implode the remaining array elements and just append the popped value.
$contributors = array(
array(
"name" => 'John',
"role" => 'author',
),
array(
"name" => 'Gail',
"role" => 'author',
),
array(
"name" => 'Jose',
"role" => 'author',
),
array(
"name" => 'Thomas',
"role" => 'author',
),
array(
"name" => 'Beth',
"role" => 'illustrator',
),
array(
"name" => 'Mary',
"role" => 'producer',
),
array(
"name" => 'Criss',
"role" => 'producer',
),
);
//Grouped the names according to role
$grouped = array_reduce($contributors, function($c, $v) {
if ( !isset( $c[ $v['role'] ] ) ) $c[ $v['role'] ] = array();
$c[ $v['role'] ][] = $v['name'];
return $c;
}, array());
//Construct final Array
$final = array();
foreach( $grouped as $key => $group ) {
$last = array_pop( $group );
if ( count( $group ) == 0 ) $final[ $key ] = $last; /* One one name on the role, no need to do anything*/
else $final[ $key ] = implode( ", ", $group ) . " and " . $last;
}
echo "<pre>";
print_r( $final );
echo "</pre>";
This will result to:
Array
(
[author] => John, Gail, Jose and Thomas
[illustrator] => Beth
[producer] => Mary and Criss
)
You can now use it as
echo 'Written by ' . $final["author"] . '. Designed by ' . $final["illustrator"] . '. Produced by ' . $final["producer"];
And will result to:
Written by John, Gail, Jose and Thomas. Designed by Beth. Produced by
Mary and Criss
You can try like this -
$contributors = array(
array(
'name' => 'John',
'role' => 'author',
),
array(
'name' => 'Gail',
'role' => 'author',
),
array(
'name' => 'Ali',
'role' => 'author',
),
array(
'name' => 'Beth',
'role' => 'illustrator',
)
);
#This function prepare array to expected String
function PrepareArray($data){
$combined = '';
if (count($data)>1) {
$last = array_slice($data, -1);
$first = join(', ', array_slice($data, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
$combined = join(' and ', $both);
}else{
$combined = implode('', $data);
}
return $combined;
}
$authors = array();
$designers = array();
foreach ($contributors as $key => $value) {
if ($value['role']=='author') {
$authors[] = $value['name']; #Keep Authors name in Array
}else if ($value['role']=='illustrator') {
$designers[] = $value['name']; #Keep Designers name in Array
}
}
$authors = PrepareArray($authors);
$designers = PrepareArray($designers);
echo "Written by {$authors}. Designed by {$designers}.";
Output :
Written by John, Gail and Ali. Designed by Beth.
Try below code:
<?php
$contributors = array(
0 => array(
'name' => 'John',
'role' => 'author',
),
1 => array(
'name' => 'Gail',
'role' => 'author',
),
2 => array(
'name' => 'Beth',
'role' => 'illustrator',
),
3 => array(
'name' => 'Albert',
'role' => 'author',
),
);
$labels = ['author'=>'Written by', 'illustrator'=>'Designed by', 'producer'=>'Produced by'];
$new_contributors = [];
foreach($contributors as $cont){
$new_contributors[$cont['role']][] = $cont['name'];
}
$str = '';
foreach($labels as $role=>$label){
if(isset($new_contributors[$role]) && is_array($new_contributors[$role])){
$str .= ' '.$label.' ';
foreach($new_contributors[$role] as $key=>$new_contributor){
$count = count($new_contributors[$role]);
if(($count - $key) == 1 ){
$str .= ' and ';
$str .= $new_contributor;
}else if(($count - $key) == 2){
$str .= $new_contributor;
}else{
$str .= $new_contributor.', ';
}
}
}
}
echo $str;

how can i use foreach methord in this piece of code

how can i print the whole multidimensional array by using foreach?
<?php
$shop=array // main array
(
"laptop"=>array
(
"conpaq",
"IBM",
"DELL",
"Lenovo"
),
"printer"=>array
(
"canon",
"Hp"
),
"Tabs"=>array
(
"Hp",
"Dell",
"deny"
)
);
This one is a simple list using recursion, it also have tabs to make it more clear when there's a new array-group.
Please try it and adjust for your code.
$shop = array(
'computers' => array(
'dell' => array(
'i7' => array(
'model1' => 'Model 1',
'model2' => 'Model 2',
),
'i5' => 'Model 1'
),
'hp' => array(
'model1' => 'Model 1'
)
),
'printers' => array(
'Epson' => 'Model 1'
)
);
function printProducts($products, $tabsCount = 0){
$result = ''; $tabs = '';
for($i = 0; $i < $tabsCount; $i++){ $tabs .= ' '; }
foreach($products AS $index=>$product){
if(is_array($product)){
$result .= $tabs.$index.'<br>';
$result .= printProducts($product, $tabsCount+1);
}else{
$result .= $tabs.$product.'<br>';
}
}
return $result;
}
echo printProducts($shop);
Ask if there is something you don't understand.
for 2 levels and without recursion. Recusion would be better but this will work.
foreach($shop as $value) {
if (is_array($value)) {
foreach($shop as $value) {
echo "$value<br />";
}
} else {
echo "$value<br />";
}
}
?>

output error in php json-decode

my php code generate a non-Valid json output error
my php code :
$questions = array();
while($question = mysql_fetch_array($result, MYSQL_ASSOC)) {
$questions[] = array('question'=> $question);
}
print_r ($questions);
$newQuestions = array('questions' => array());
foreach($questions as $key => $question){
$newQuestion = array(
'question' => $question['question']['question'],
'correct' => $question['question']['correct'],
'answers' => array(
$question['question']['answer1'],
$question['question']['answer2'],
$question['question']['answer3'],
$question['question']['answer4']
)
);
$newQuestions['questions'][] = $newQuestion;
}
$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);
echo '<br/><br/>';
echo $output;
table fields :
Question :
correct :
answer 1 :
answer 2 :
answer 3 :
answer 4 :
Example :
Question : is php a good language ?
correct : 1
answer 1 : yes
answer 2 : no
answer 3 : maybe
answer 4 : good
the output is OK, and formated as I want.
output sample : http://pastebin.com/eefS7KYW
I am sure my php code is correct but I don't know where is exactly the issue !!
==============
Fixed : it was just two echo $output !
Seems like you are doing a lot of variable passing which gets very confusing, very quickly. Especially when all the variables are iterations of 'question'. It appears that you are creating an array from information pulled from a database in the format [questions[question,correct,answers[1,2,3,4]]] This code format may work better?
$newQuestions = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$newQuestions['questions'][] = array(
'question' => $row['question'],
'correct' => $row['correct'],
'answers' => array(
$row['answer1'],
$row['answer2'],
$row['answer3'],
$row['answer4']
)
);
}
$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);
echo '<br/><br/>';
echo $output;
Had a semicolon in the wrong place.Fixed the code above and test the code with the following:
<?php
$array = array(
array('question'=>'Question1',
'correct'=>3,
'answer1' => 'Q1Answer1',
'answer2' => 'Q1Answer2',
'answer3' => 'Q1Answer3',
'answer4' => 'Q1Answer4'
),
array('question'=>'Question2',
'correct'=>3,
'answer1' => 'Q2Answer1',
'answer2' => 'Q2Answer2',
'answer3' => 'Q2Answer3',
'answer4' => 'Q1Answer4'
),
array('question'=>'Question3',
'correct'=>3,
'answer1' => 'Q3Answer1',
'answer2' => 'Q3Answer2',
'answer3' => 'Q3Answer3',
'answer4' => 'Q1Answer4'
)
);
$newQuestions = array();
//while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($array as $row){
$newQuestions['questions'][] = array(
'question' => $row['question'],
'correct' => $row['correct'],
'answers' => array(
$row['answer1'],
$row['answer2'],
$row['answer3'],
$row['answer4']
)
);
}
print_r($newQuestions);
$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);
echo '<br/><br/>';
echo $output;
?>

How to echo checkbox group with multidimentional array

I need help to get the data from my checkbox-group with multidimensional array options to reflect in my post page(single.php code). Radio type is working well but the checkbox-group type is not. I added on the bottom the sample code found in my single.php for the radio type which query the data to my post page for your reference.
Here's the array from my metabox.php code:
<?php
// array
$prefix = 'wtf_';
$meta_box = array( 'id' => 'site',
'title' => 'Program Details',
'page' => 'post',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array('name' => 'Principal Return',
'desc' => 'Principal Return After Expiry or Not',
'id' => $prefix . 'principal',
'type' => 'radio',
'options' => array(
array('name' => ' Yes ', 'value' => 'Yes-after expiry'),
array('name' => ' No ', 'value' => 'No-included on the interest')
)
),
array(
'name' => 'Compounding',
'desc' => 'Choose if compounding is allowed or not',
'id' => $prefix . 'compounding',
'type' => 'radio',
'options' => array(
array('name' => ' Yes ', 'value' => 'Allowed'),
array('name' => ' No ', 'value' => 'Not Allowed'),
array('name' => ' Re-purchase', 'value' => 'Yes thru re-purchase')
)
),
array ('name' => 'Payment Processors',
'desc' => 'Payment Processsor Accepted',
'id' => $prefix.'processors',
'type' => 'checkbox_group',
'options' => array(
array('label' => ' Liberty Reserve ', 'value' =>'LR'),
array('label' => ' SolidTrustPay ', 'value' =>'STP'),
array('label' => ' EgoPay ', 'value' =>'EgoPay'),
array('label' => ' Perfect Money ', 'value' =>'PM'),
array('label' => ' Payza ', 'value' =>'Payza'),
array('label' => ' PayPal ', 'value' =>'PayPal'),
array('label' => ' Bankwire ', 'value' =>'Bankwire')
))))
// Callback function to show fields in meta box
function mytheme_show_box() {
global $meta_box, $post;
// Use nonce for verification
echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($meta_box['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
'<td>';
switch ($field['type']) {
case 'text':
echo $statetemt;
break;
case 'textarea':
echo $statetemt;
break;
case 'select':
echo $statetemt;
break;
case 'radio':
foreach ($field['options'] as $option) {
echo $statetemt; }
break;
case 'checkbox':
foreach ($field['options'] as $option) {
echo $statetemt;}
break;
case 'checkbox_group':
foreach ($field['options'] as $option) {
echo '<input type="checkbox" value="'.$option['value'].'" name="'.$field['id'].'[]" id="'.$option['value'].'"',$meta && in_array($option['value'], $meta) ? ' checked="checked"' : '',' />',$option['label']; }
echo '<br /><span class="description">'.$field['desc'].'</span>';
break;
}
//From my single.php code <<<<=================
<div class="sdinfo"><strong>Principal Return</strong>:<span><?php $principal = get_post_meta(get_the_ID(), 'wtf_principal', true);
if (isset($principal[0])) {
echo $principal ;
} else if (isset($principal[1])) {
$principal = get_post_meta(get_the_ID(), 'wtf_principal', true);
echo $principal;
} else {_e('Not Available');} ?></span></div>
<div class="sdinfo"><strong>Program Started</strong>:<span> <?php $started = get_post_meta(get_the_ID(), 'wtf_started', true); if (isset($started[0])) { echo $started;
} else {_e('Not Available');} ?></span></div>
<div class="sdinfo"><strong>Compounding</strong>:<span>
<?php $compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
if (isset($compounding[0])) {
echo $compounding ;
} else if (isset($compounding[1])) {
$compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
echo $compounding;
} else if (isset($compounding[2])) {
$compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
echo $compounding;
} else {_e('Not Available');} ?></span></div>
?>
This give me an output from post meta like this:
admin screenshot
This is the output from my post page. :
post page screenshot
Please help!.. I am not a programmer hope you can share me an answer in much details.Thank you in advance!
All what you need is point an array using var_dump($array) to check where and what data you need from arrays fields.
Second you need to get foreach() function. For example you want grab an array of data:
'priority' => 'high', should be as example:
echo $meta_box["priority"] which will result as value of array: high
If you are not sure and not familiar with array use as simple:
foreach ($meta_box as $arr)
{
var_dump($arr);
#then play and manipulate how to grab a fields a data:
foreach ($arr["fields"][""] as $fa)
{
var_dump($fa["name"]);
var_dump($fa["desc"]);
var_dump($fa["desc"]);
}
#...
}
Learn how to grab via var_dump() if you unsure with array of data.
Payment Processors LR STP EgoP
echo $meta_box["fields"][""]["name"];
Than you need grab a data of an array:
foreach ($meta_box["fields"][""]["options"] as $options)
{
foreach ($options as $options_key)
{
foreach ($options_key as $opt_val)
{
$result .= ' '.$opt_val;
}
}
}

Categories