$array = (
array('1231415'=>array('foo'=>'bar', 'test'=> 1)),
array('32434'=>array('foo'=>'bar', 'test'=> '0')),
array('123244'=>array('foo'=>'bar', 'test'=> 0)),
array('193928'=>array('foo'=>'bar', 'test'=> 1))
);
I have an array that has (many) random keys, the ID number. I need to test each array within if 'test' = 1, and so I made a foreach loop.
foreach ($array as $sub) {
if ($sub['test'] == '1' ) {
echo 'User: ' . $sub . ' has test = 1';
}
}
This works, but it returns 'User: Array has test = 1'
How on earth to I get which ID number, (that random number) has test=1 in it?
I tried doing $array as $sub=>$value, but for some reason it just makes the foreach not work. Thank you!
Use this foreach syntax instead:
foreach ($array as $key => $sub) {
if ($sub['test'] == '1' ) {
echo 'User: ' . $key . ' has test = 1';
}
}
This assumes that the data is in the form:
$array = array(
'1234' => array('test' => 1),
'5678' => array('test' => 2)
);
If you need to keep your data as it is now, you'll need to use something more like:
foreach ($array as $item) {
list($key, $info) = $item;
if ($info['test'] == 1) {
echo 'User: ' . $key . ' has test = 1';
}
}
There are 2 problems with your code.
1) Your array declaration is slightly messed up. Try this:
$array = array(
'1231415'=>array('foo'=>'bar', 'test'=> 1),
'32434'=>array('foo'=>'bar', 'test'=> 0),
'123244'=>array('foo'=>'bar', 'test'=> 0),
'193928'=>array('foo'=>'bar', 'test'=> 1)
);
2) In your foreach, you're losing the id key. Try this:
foreach ($array as $id => $sub) {
if ($sub['test'] == 1) {
echo "User: " . $id . " has test = 1\n";
}
}
In my test the above outputs:
User: 1231415 has test = 1
User: 193928 has test = 1
Related
Is it possible to iterate using foreach loop with key=>value but assign different variable to each lines output. I am looking for something like this:
foreach($counts as $key => $value){
$c = $key . ' => ' . $value;
$d = $key . ' => ' . $value;
};
when the sample output from vardump($counts) looks like:
array(3) { ["Type_1"]=> int(1) ["Type_2"]=> int(3) ["Type_3"]=> int(1) }
Each
int() is a quantity so ideally I would like the output to look like
$c = 1
$d = 3
$e = 1
also ok with
$c = Type_1 1
$d = Type_2 3
$e = Type_3 1
Either way, I want to access the quantities by reference the variable directly.
Your best bet is to use an array, that's what they are for:
foreach($counts as $key => $value){
$output[] = $key . ' => ' . $value;
};
It depends on why you are doing this, how you will use it and what you know, but why not use the key:
foreach($counts as $key => $value){
$output[$key] = $key . ' => ' . $value;
};
You could create an array of variable names and shift one off each time and use that, however you will never know how many there are and this is very bad practice:
$vars = range('a', 'z');
foreach($counts as $key => $value){
${array_shift($vars)} = $key . ' => ' . $value;
};
In your example you would have $a, $b and $c.
Not sure what your purpose here but you can assign different variable to each lines output by using reference variable that stores the value of the $variable inside it, that is $key in your code like below. It will help in case you know what keys will be in counts array all the time.
$counts = [ "Type_1" => 1,"Type_2"=>3, "Type_3"=> 1 ];
foreach($counts as $key => $value){
$$key = $key . ' => ' . $value;
};
echo $Type_1;
echo $Type_2;
echo $Type_3;
Output will be
Type_1 => 1
Type_2 => 3
Type_3 => 1
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);
I've got this array:
Array
(
[0] => Array
(
[name] => System
[order] => 1
[icon] => stats.svg
[0] => Array
(
[title] => Multilingual
)
[1] => Array
(
[title] => Coloring
)
[2] => Array
(
[title] => Team work
)
[3] => Array
(
[title] => Tutorials
)
)
)
I want to loop into this to show the section name and after all the features containing in the following array.
So, this is what I made:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
foreach (array_values($info) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
It works except for the first third <li> where I have the first char of name, order and icon value.
Do you know why ?
Thanks.
array_values return value of array so for info values is name, order, icon, 0, 1, ...
Your values foreach is wrong if you just want print title you can use:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
//Remove some keys from info array
$removeKeys = array('name', 'order', 'icon');
$arr = $info;
foreach($removeKeys as $key) {
unset($arr[$key]);
}
foreach (array_values($arr) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
In php, array_values means all the values of the array. So array_values($info) is array($info['name'], $info['order'], $info['icon'], $info[0], $info[1], $info[2], $info[3])
in your example, you can skip the non-integer keys of the $info to get your titles:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info[] = array('title'=>'Multilingual');
$info[] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info as $k => $item) {
if(!is_int($k)) continue;
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
BUT, your original data structure is not well designed and hard to use. For a better design, you can consider the following code, move your items to a sub array of $info:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info['items'] = array();
$info['items'][] = array('title'=>'Multilingual');
$info['items'][] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info['items'] as $item) {
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
Sample output of the two demos:
System
<ul class="menu-vertical bullets">
<li>Multilingual</li>
<li>Coloring</li>
</ul>
It works except for the first third li where I have the first char of name, order and icon value. Do you know why ?
Why you see first chars of the values of 'name', 'order', 'icon'? Let see how PHP works.
Take the first loop as an example: foreach (array_values($info) as $i => $key)
Then $i == 0, $key == 'System'
We know that $key[0] == 'S', $key[1] == 'y', $key[2] == 's', etc.
Then you try to access $key['title'], but the string 'title' is not valid as a string offset, so it is converted to an integer by PHP: intval('title') == 0.
Then $key['title'] == $key[intval('title')] == 'S'
That's what you see.
array_value() returns the values of the array, here you will get the value of the array $info and what I understand is that is not what you need. See details for array_value().
You can check if the key for the $info is an integer. if yes, echo the title. Give this a try.
foreach ($features as $feature => $info) {
echo $info['name'].'<ul class="menu-vertical bullets">';
foreach ($info as $key => $value) {
if (is_int($key)) {
echo '<li>'.$key['title'].'</li>';
}
}
echo '</ul>';
}
print "<ul>";
foreach ($arr as $value) {
echo("<li>" . $value[storeid] . " " . ($value[dvdstock] + $value[vhsstock]) . "</li>");
}
print "</ul>";
Will output
•2 20
•2 10
•1 20
•1 20
•1 10
I was wondering how I would adapt this loop so it outputs the total values for each &value[storeid]
•1 50
•2 30
Thanks very much :)
Use another array to calculate the values you want:
// setup a quick place to store the data
$stores = array();
foreach ($arr as $value) {
if(!isset($stores[$value['storeid']])){ // init check required to avoid Notices
$stores[$value['storeid']] = $value['dvdstock'] + $value['vhsstock'];
}else{
$stores[$value['storeid']] += $value['dvdstock'] + $value['vhsstock'];
}
}
ksort($stores); // sort by storeid ASC
print "<ul>";
// loop through the new data
foreach ($stores as $id => $value) {
echo("<li>" . $id . " " . ($value) . "</li>");
}
print "</ul>";
Demo Link
If you are getting the data from an SQL database then you should do this using SUM() functions in the SQL as it is more efficient. If the data source is from somewhere else you should do something like this:
//Sum data
foreach ($arr as $value) {
if (!isset($sums[$value['storeid']])) { // init check required to avoid Notices
$sums[$value['storeid']] = $value['dvdstock'] + $value['vhsstock'];
} else {
$sums[$value['storeid']] += $value['dvdstock'] + $value['vhsstock'];
}
}
ksort($sums); // sort by storeid ASC
print "<ul>";
foreach ($sums as $key => $sum) {
echo("<li>$key $sum</li>");
}
print "</ul>";
Demo Link
It is a for loop and you have to make two of them. First to compute the sum and then to iterate over these values:
$data = array();
foreach ($arr as $value) {
if (!isset($data[$value['storeid']])) { // init check required to avoid Notices
$data[$value['storeid']] = $value['dvdstock'] + $value['vhsstock'];
} else {
$data[$value['storeid']] += $value['dvdstock'] + $value['vhsstock'];
}
}
ksort($data); // sort by storeid ASC
print "<ul>";
foreach ($data as $storeid => $sum) {
echo('<li>' . $storeid . ' ' . ($sum) . '</li>');
}
print "</ul>";
Demo Link
Btw one word about strings:
Either use single quotes ' with concatenation .: 'foo: ' . $bar.
Or double quotes " and put the variables inside the string: "foo: $bar".
<?php
$sums = array();
foreach ($arr as $value)
{
$sums[$value['storeid']] += $value['dvdstock'];
}
print_r($sums);
?>
Correct version:
<?php
$initial = array (
array (
'id' => 1,
'amount' => 10
),
array (
'id' => 1,
'amount' => 10
),
array (
'id' => 2,
'amount' => 20
),
array (
'id' => 2,
'amount' => 20
),
array (
'id' => 2,
'amount' => 20
),
);
$result = array ();
foreach ($initial as $value) {
$result[$value['id']] += $value['amount'];
}
print_r($result);
?>
I have a huge array from a json_decode result (assoc set to true) and have the following code to check if (one of the arrays within, a random serial) has the key 'set_true'
$out = "";
foreach ($array as $sub) {
//$out[] = $sub['set_true'];
if (in_array($sub['set_true'], $sub) && $sub['set_true'] == '1' ) {
$out[] = 'User: ' . $sub . ' has set_true = 1';
}
}
That code lists all the users with that array key set to 1, but $sub returns 'array' and not the current key I'm on! (the random serial)
How do I return it?
If you are looping through an array with foreach, and want to know the key you're currently on in the loop, you can use this syntax :
foreach ($array as $key => $value) {
// $key contains the name of the current key
// and $value the current value
}
What's up with your in_array call? I don't think that is correct. Why do you look for $sub in $sub?
I think you mean:
$out = "";
foreach ($array as $key => $sub) {
if (array_key_exists('set_true', $sub) && $sub['set_true'] == '1' ) {
$out[] = 'User: ' . $key . ' has set_true = 1';
}
}