the following produces no output, when really it should show a list including Milk, Cheese and Yoghurt. It is probably something really simple, I just can't see it.
<?php
$FoodList=array();
$newArray =array();
echo "<p>";
$Dairy= array(
'a' => 'Milk',
'b' => 'Cheese',
'c' => 'Yoghurt',
);
$Fruit = array(
'd' => 'Apples',
'e' => 'Oranges',
'f' => 'Grapefruit',
);
$GlutenFree = array(
'g' => 'GF Cookies',
'h' => 'GF Pancakes',
'i' => 'GF Bread',
);
$Sweets = array(
'j' => 'Musk Sticks',
'k' => 'Caramels',
'l' => 'Chocolate',
);
if ($_POST['running'] == 'yes')
{
$newArray = array_merge($FoodList, $Dairy);
foreach ($newArray as $key => $value)
{
echo $value;
}
}
echo "<p>";
?>
This may because the FoodList Array does not have anything in it, so I will look into that, but I have a strong feeling it is related to something else.
Your "bug" must be coming from the line, the array merge is fine:
if ($_POST['running'] == 'yes')
foreach($Dairy as $key => $value)
{
echo $value;
}
Related
I have an array as
$apps = array(
array(
'id' => '2',
'name' => 'Popcorn'
),
array(
'id' => '1',
'name' => 'EveryCord'
),
array(
'id' => '2',
'name' => 'AirShou'
),
Here I want to print names where id="2". So I tried it with following code.
foreach ( $apps as $var ) if ($var['id'] == "2") {
echo $var['name']
}
The problem is that it only print first result of the array as
"Popcorn".
But I want to extract all result which are
"Popcorn and Airshou"
How can I fix this. Can someone help me !
Try this;
$apps = [
['name' => 'Fish', 'id' => 2],
['name' => 'Chips', 'id' => 1],
['name' => 'Sticks', 'id' => 2],
];
$using = [];
foreach ( $apps as $var ) {
if ($var['id'] == "2") {
$using[] = $var['name'];
}
}
echo implode(" and ", $using);
RESULT:
You can create a sample array.
And append the name to it, if it is id=2
Code:
$apps = [
['id' => '2', 'name' => 'Popcorn'],
['id' => '1', 'name' => 'EveryCord'],
['id' => '2', 'name' => 'AirShou']
];
$names = [];
if (! empty($apps)) {
foreach ($apps as $elem) {
if ($elem['id'] == 2) {
$names[] = $elem['name'];
}
}
}
$finalName = ! empty($names) ? implode(' and ', $names) : '';
echo '<pre>';print_r($finalName);echo '</pre>';
// Output: Popcorn and AirShou
You can filter the array on the item id and then retrieve the column name:
array_column(array_filter($apps, function($v){return '2' === $v['id'];}), 'name')
result:
array(2) {
[0] =>
string(7) "Popcorn"
[1] =>
string(7) "AirShou"
}
Change your loop by this code, and you will got both names,
foreach ( $apps as $var ){
if ($var['id'] == "2") {
echo $var['name'];
}
}
Just grab names in array then implode it like this:
$temp = array();
foreach ( $apps as $var ) if ($var['id'] == "2") {
$temp[] = $var['name']
}
echo implode(' and ', $temp);
I have following PHP code, to create JSON with foreach out of an array:
$array = array('one', 'two', 'three', 'four');
foreach ($array as $key => $value) {
$temp = array(
'text' => 'Hello',
'text1' => 5,
'collect' => array(
$value => array(
'xx' => 'yy',
'key' => $key
)
)
);
echo json_encode($temp);
}
The Output is this:
{
"text":"Hello",
"text1":5,
"collect":{"one":{"xx":"yy","key":0}}
}
{
"text":"Hello",
"text1":5,
"collect":{"two":{"xx":"yy","key":1}}
}
{
"text":"Hello",
"text1":5,
"collect":{"three":{"xx":"yy","key":2}}
}
{
"text":"Hello",
"text1":5,
"collect":{"four":{"xx":"yy","key":3}}
}
But i want this:
{
"text":"Hello",
"text1":5,
"collect": {
"one":{"xx":"yy","key":0},
"two":{"xx":"yy","key":1},
"three":{"xx":"yy","key":2},
"four":{"xx":"yy","key":3}
}
}
I get single 4 single JSON Objects, but i need only one with an collect object.
I don't get it...
I'd like to educate readers on a couple alternative methods as well as highlight that the other two answers needlessly instantiate the collect subarray prior to the loop (Sahil's answer does this twice for some reason).
The initial input array and the static elements of the result array should be placed at the start as the other answers do. Purely due to personal preference, I'll be using short array syntax.
Inputs:
$array=['one','two','three','four'];
$result=['text'=>'Hello','text1'=>5]; // <-- no 'comment' element declared
Now for the different methods that traverse $array and build the dynamic elements of the result.
Method #1: array_walk()
array_walk($array,function($v,$k)use(&$result){
$result['collect'][$v]=['xx'=>'yy','key'=>$k];
});
Method #2: array_map()
array_map(function($k,$v)use(&$result){
$result['collect'][$v]=['xx'=>'yy','key'=>$k];
},array_keys($array),$array);
Array map is less efficient because it requires an additional array to be passed to the function.
Method #3: foreach()
foreach($array as $k=>$v){
$result['collect'][$v]=['xx'=>'yy','key'=>$k];
}
$result at this point looks like this:
array (
'text' => 'Hello',
'text1' => 5,
'collect' => array (
'one' => array ( 'xx' => 'yy', 'key' => 0 ),
'two' => array ( 'xx' => 'yy', 'key' => 1 ),
'three' => array ( 'xx' => 'yy', 'key' => 2 ),
'four' => array ( 'xx' => 'yy', 'key' => 3 )
)
)
foreach() is the simplest and easiest to read for this case, but it important to understand and compare versus php's array functions to ensure you are using the best method for any given project.
For anyone wondering what the & is doing in use(&$result), that is a reference which is used in the anonymous function (aka closure) to make the $result variable "modifiable" within the function.
Finally convert to json using json_encode() and display with echo:
echo json_encode($result);
All of the above methods product the same desired output:
{"text":"Hello","text1":5,"collect":{"one":{"xx":"yy","key":0},"two":{"xx":"yy","key":1},"three":{"xx":"yy","key":2},"four":{"xx":"yy","key":3}}}
Here is the Demo of all three methods
Try this simple code ,in which we have a declaration before foreach.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$array = array('one', 'two', 'three', 'four');
$temp = array(
'text' => 'Hello',
'text1' => 5,
'collect' => array()
);
$collect = array();
foreach ($array as $key => $value)
{
$collect[$value] = array(
'xx' => 'yy',
'key' => $key
);
}
$temp["collect"]=$collect;
echo json_encode($temp);
Output:
{
"text": "Hello",
"text1": 5,
"collect": {
"one": {
"xx": "yy",
"key": 0
},
"two": {
"xx": "yy",
"key": 1
},
"three": {
"xx": "yy",
"key": 2
},
"four": {
"xx": "yy",
"key": 3
}
}
}
You need to loop through and append these value arrays to the 'collect' key of your temp array.
$array = array('one', 'two', 'three', 'four');
$temp = array(
'text' => 'Hello',
'text1' => 5,
'collect' => array()
);
foreach ($array as $key => $value) {
$temp['collect'][$value] = array(
'xx' => 'yy',
'key' => $key
);
}
echo json_encode($temp);
Here is the demo: https://eval.in/788929
I got array like this
$specials = array( 1 => array('word' => array('first', 'two', 'three'), 'digit' => array(1,2,3)),
2 => array('word' => array('four','five', 'six'), 'digit' => array(4,5,6)),
3 => array('word' => array('seven', 'eight', 'nine'), 'digit' => array(7,8,9)),
4 => array('word' => array('ten','eleven', 'twelve'), 'digit' => array(10,11,12))
);
and why i got to foreach 3 times like this
foreach($specials as $val) {
foreach($val as $valData) {
foreach($valData as $value) {
echo $value.'<br/>';
}
}
}
But how to loop or foreach correctly and with their index name like this ?
echo $value['word'];
echo $value['digit'];
i got error warning if echo $value['digit']
Warning: Illegal string offset 'digit' in ~/public_html/test/array.php on line 58
i need those output for different HTML and CSS each Value
<div class="digit"><?=$value['digit']?></div>
<div class="word"><?=$value['word']?></div>
foreach($specials as $val) {
foreach($val as $key => $valData) {
// $key is now either 'word' or 'digit'
foreach($valData as $value) {
echo "<div class='$key'>$value</div>";
}
}
}
I got two associative, multidimensional arrays $arrayOffered and $arraySold. I would like to merge them under certain conditions:
if value of key 'item' from $arrayOffered exists in $arraySold, both elements should be included in array $result. If for 1 element from $arrayOffered there are 3 elements in $arraySold, I should get also 3 elements in $result.
otherwise, element from $arrayOffered should be added into $result.
One element from $arrayOffered can have >1 equivalents in $arraySold. They should be joined in the way shown below.
Input data:
$arrayOffered = array(
0 => array('item' => 'product_1', 'Category' => 'ABC'),
1 => array('item' => 'product_2', 'Category' => 'DEF')
);
$arraySold = array(
0 => array('item' => 'product_1', 'ItemsSold' => '2', 'ItemsReturned' => 1), //arrays in this array can contain up to 30 elements
1 => array('item' => 'product_1', 'ItemsSold' => '1')
);
Desired result:
$desiredResult = array(
0 => array('item' => 'product_1', 'Category' => 'ABC', 'ItemsSold' => '2', 'ItemsReturned' => 1),
1 => array('item' => 'product_1', 'Category' => 'ABC', 'ItemsSold' => '1'),
2 => array('item' => 'product_2', 'Category' => 'DEF')
);
I got stuck on something like:
$result = array();
foreach ($arrayOffered as $keyOffered => $offeredSubArr)
{
$item = $offeredSubArr['item'];
foreach($arraySold as $keySold => $soldSubArr)
{
if(isset($soldSubArr['item']) && $soldSubArr['item'] == $item)
{
$i = 0;
$test = array_merge($offeredSubArr, $soldSubArr);
$result[$i][] = $test;
$i++;
}
else
{
$result[$i][] = $offeredSubArr;
$i++;
}
}
}
Problem:
- output array isn't formatted the way I wanted
- I know I'm not going in the right direction. Can you please give me a hint?
This is an option, since you have this $arrayOffered as a kind of master file I suggest to build a hash with this array and use later on the foreach look for sold array.
$arrayOffered = array(
0 => array('item' => 'product_1', 'Category' => 'ABC'),
1 => array('item' => 'product_2', 'Category' => 'DEF')
);
$arraySold = array(
0 => array('item' => 'product_1', 'ItemsSold' => '2', 'ItemsReturned' => 1), //arrays in this array can contain up to 30 elements
1 => array('item' => 'product_1', 'ItemsSold' => '1')
);
//Build a hash to get the extra properties
$hashArray = array();
foreach ($arrayOffered as $offered) {
$hashArray[$offered['item']]=$offered;
}
$resultArray = array();
foreach ($arraySold as $sold) {
$hashItem = $hashArray[$sold['item']];
// you dont want this sold flag on your final result
unset($hashItem['sold']);
$resultArray[]=array_merge($hashItem,$sold);
$hashArray[$sold['item']]['sold']= true;
}
//Add all the missing hash items
foreach($hashArray as $hashItem){
if(!isset($hashItem['sold'])){
$resultArray[]=$hashItem;
}
}
print_r($resultArray);
Test sample
http://sandbox.onlinephpfunctions.com/code/f48ceb3deb328088209fbaef4f01d8d4430478db
$result = array();
foreach ($arrayOffered as $keyOffered => $offeredSubArr)
{
$item = $offeredSubArr['item'];
foreach($arraySold as $keySold => $soldSubArr)
{ $i = 0;
if(isset($soldSubArr['item']) && $soldSubArr['item'] == $item)
{
$test = array_merge($offeredSubArr, $soldSubArr);
$result[$i][] = $test;
}
else
{
$result[$i][] = $offeredSubArr;
}
$i++;
}
}
$result = $result[0];
echo '<pre>'; print_r($result); die();
Well i will try to follow your logic although there is simpler solutions.
First of all we will need to search in a multidimentional array thats why we will need the followed function from this so thread
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Next after small changes:
$i you don't need to make it zero on every loop just once so place it outside
unnecessary [] ($result[$i][]) you don't need the empty brackets no reason to create an extra table in the $i row since what you add there, the $test is already table itself
Adding the last loop coz when sth is not in the second table it will be added in your new table in every loop and as far as i get you don't want that kind of duplicates
We have the following code:
$arrayOffered = array(
0 => array('item' => 'product_1', 'Category' => 'ABC'),
1 => array('item' => 'product_2', 'Category' => 'DEF')
);
$arraySold = array(
0 => array('item' => 'product_1', 'ItemsSold' => '2', 'ItemsReturned' => 1), //arrays in this array can contain up to 30 elements
1 => array('item' => 'product_1', 'ItemsSold' => '1')
);
$i = 0;
$result = array();
foreach ($arrayOffered as $keyOffered => $offeredSubArr)
{
$item = $offeredSubArr['item'];
foreach($arraySold as $keySold => $soldSubArr)
{
if(isset($soldSubArr['item']) && $soldSubArr['item'] == $item)
{
$test = array_merge($offeredSubArr, $soldSubArr);
$result[$i] = $test;
$i++;
}
}
}
foreach ($arrayOffered as $value)
{
if (!in_array_r($value['item'], $result))
{
$result[$i] = $value;
$i++;
}
}
print_r($result);
Which as far as i tested gives the wanted result.
How do I check if any of the keys in foreach loop exists in another array's value ?
Array 1 I want to check
$array1 = array(
'a' => '1',
'b' => '2',
'c' => '3',
);
And the Array 2 which Array 1 should be compared to
$reserved_words = array('b');
What I want is to check whether the conditional check is TRUE to apply specific actions. My code looks like this now:
foreach( $array1 as $key => $value )
{
// Check for reserved words
if( in_array($key, $reserved_words)
{
// Some action
}
// Code...
}
I can't find anything similiar to array_key_exists, probably I am missing something.
I want to check it by simply doing this:
if( array_value_exists($value, $reserved_words) )
But the problem is that no array_value_exists function is available.
You forgot first the as keyword in your foreach header and you missed a ) in your if statement.
So this should work:
<?php
$array1 = array(
'a' => '1',
'b' => '2',
'c' => '3',
);
$reserved_words = array('b');
foreach( $array1 as $key => $value ) {
//^^Here 'as' keyword
if( in_array($key, $reserved_words)) {
echo $key; //^Here ')' closed if statement
}
}
?>
$array1 = array(
'a' => '1',
'b' => '2',
'c' => '3',
);
$reserved_words = array('b');
>>> array_intersect_key($array1, array_flip($reserved_words));
=> [
"b" => "2"
]
you are missing the 'as' keyword. Please put the code like below
foreach($array1 as $key => $val){
if(in_array($key, $reserved_words)){
echo "yes";
} else {
echo "no";
}
}