Using a variable outside foreach with if statement? - php

This code should explain it all..
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $k => $type) {
$preview[] = $type['type'];
}
if ($preview == 'header_preview'){
echo $preview;
// I will loop content here based on the $section loop NOT the $type loop
}
}
I just need to get each $section['fields'] then outside that loop, which again gets a list of all the $section['fields'] then use one of those field types to create an if statement. The above is non working, I will show you working code here.
foreach($this->sections as $k => $section){
foreach ($section['fields'] as $k => $type) {
if ($type['type'] == 'header_preview'){
//I work but im in a nested loop I need out
}
}
//The main loop here.. the above loop is just to setup data to use inside this loop? Make sense? I hope!
}
I hope this makes sense...
Snippet of var_dump $this->sections
array(26) { ["general"]=> array(3) { ["title"]=> string(7) "General" ["icon"]=> string(106) "img/icons/sub.png" ["fields"]=> array(5) { [0]=> array(6) { ["id"]=> string(10) "responsive" ["type"]=> string(6) "switch" ["title"]=> string(35) "Responsive" ["desc"]=> string(10) "Responsive" ["options"]=> array(2) { [1]=> string(2) "On" [0]=> string(3) "Off" }

It could be possible $k has been duplicated and therefore the loop doesn't know what to do. You can try changing $k to $x, see if it works.
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $x => $type) {
$preview[] = $type['type'];
}
foreach($preview as $elem){
if ($elem == 'header_preview'){
echo($elem);
}
}
}

Hmm... Maybe
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $x => $type) {
$preview[] = $type['type'];
}
if(!in_array('header_preview', $preview)){
// Here $preview DOES NOT contain 'header_preview'
// Do stuff
}
}

$header_preview=false;
foreach($this->sections as $k => $section){
$header_preview=false;// reset the var $header_preview
foreach ($section['fields'] as $k => $type) {
if ($type['type'] == 'header_preview') $header_preview = true;
}
if($header_preview==true){
//here you can add or extract from this array that has `header_preview` value for one of it's field type
}
}

Related

Assign Number to Foreach Variables

I want to create a list of variables from a foreach loop. I have an array like so
array(5) {
[0]=> string(105) "http://a4.mzstatic.com/us/r30/Purple5/v4/06/f2/02/06f20208-1739-4fda-c87f-171d73b912a7/screen480x480.jpeg"
[1]=> string(105) "http://a1.mzstatic.com/us/r30/Purple1/v4/53/89/0b/53890b90-c6a5-4db3-cfb9-d6314bf9cfd1/screen480x480.jpeg"
[2]=> string(105) "http://a3.mzstatic.com/us/r30/Purple1/v4/8f/31/b3/8f31b351-c9d7-e545-0ace-e09fcb390264/screen480x480.jpeg"
[3]=> string(105) "http://a5.mzstatic.com/us/r30/Purple3/v4/e7/5f/de/e75fde7b-dc5f-5b26-e531-abf07c409317/screen480x480.jpeg"
[4]=> string(105) "http://a1.mzstatic.com/us/r30/Purple3/v4/27/ce/c6/27cec64e-7e6d-7135-cc76-d0132151dadb/screen480x480.jpeg"
}
and I'd like to assign each to it's own variable. I want the final output to be something like
$var0 = "first array url";
$var1 = "second array url";
etc...
I think I want something like this but it's not quite the right syntax.
foreach ($array as $key => $value) {
$var[$key] = $value;
}
Any ideas?
foreach($array as $key => $value) {
${"var{$key}"} = $value;
}
The function you are searching for is extract.
Just use it after your foreach loop given in your example.
$vars = [];
foreach ($array as $i => $value) {
$vars['var'.$i] = $value;
}
extract($vars);

How can I output only the values of subarrays?

I have an array and I want to output some data:
array(4) {
[123]=>
array(2) {
["color"]=>
string(3) "red"
["name"]=>
string(5) "harry"
}
[345]=>
array(2) {
["color"]=>
string(4) "blue"
["name"]=>
string(4) "fred"
}
["animal"]=>
string(5) "horse"
["plant"]=>
string(4) "tree"
}
This is my solution, which I have the feeling is very unsmart:
echo "<b>These are all the colors:</b><br>";
foreach ($properties as $key => $val) {
if ($key != "plant" AND $key != "animal"){
echo $val['color']."<br>";
}
}
echo "<b>This is the animal:</b><br>";
foreach ($properties as $key => $val) {
if ($key == "animal"){
echo $val."<br>";
}
}
echo "<b>This is the plant:</b><br>";
foreach ($properties as $key => $val) {
if ($key == "plant"){
echo $val."<br>";
}
}
It gives me the desired result...
These are all the colors:
red
blue
This is the animal:
horse
This is the plant:
tree
...but I thought maybe you know a more simple solution. I am sure it must be possible to talk only to subarrays, but I couldn't find a way to do it.
Since php 5.5, you can use array_column:
$color = array_column($properties, 'color');
Since php 5.3, you can use array_map with an anonymous function, like this:
$color = array_map(function ($ar) {return $ar['color'];}, $properties);
print_r($color);
exit;
I think, Use Switch in foreach and it will help for this problem.
foreach ($properties as $key => $val) {
switch($key){
case '':
break;
}
}

php loop through array

I am trying to get certain values from an array but got stuck. Here is how the array looks:
array(2) {
[0]=>
array(2) {
["attribute_code"]=>
string(12) "manufacturer"
["attribute_value"]=>
string(3) "205"
}
[1]=>
array(2) {
["attribute_code"]=>
string(10) "silhouette"
["attribute_value"]=>
array(1) {
[0]=>
string(3) "169"
}
}
}
So from it I would like to have attribute_values, and insert it into a new array, so in this example I need 205 and 169. But the problem is that attribute_value can be array or string. This is what I have right now but it only gets me the first value - 205.
foreach ($array as $k => $v) {
$vMine[] = $v['attribute_value'];
}
What I am missing here?
Thank you!
If sometimes, attribute_value can be an array, and inside it the values, you can just check inside the loop (Provided this is the max level) using is_array() function. Example:
$vMine = array();
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) { // check if its an array
// if yes merge their contents
$vMine = array_merge($vMine, $v['attribute_value']);
} else {
$vMine[] = $v['attribute_value']; // if just a string, then just push it
}
}
I suggest you to use array_map instead of for loop. You can try something like this..
$vMine = array_map(function($v) {
return is_array($v['attribute_value']) ? current($v['attribute_value']) : $v['attribute_value'];
}, $arr);
print '<pre>';
print_r($vMine);
Try the shorthand version:
foreach ($array as $k => $v) {
$vMine[] = is_array($v['attribute_value']) ? current($v['attribute_value']):$v['attribute_value'];
}
or the longer easier to understand version, both is the same:
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) {
$vMine[] = current($v['attribute_value']);
} else {
$vMine[] = $v['attribute_value'];
}
}

add keys to php array

I'm trying to build an array for feeding my Graph. I use the code below:
$rows = $this->Website_model->getGraphDataPositives();
$_rows = array();
$i = 0;
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
$_rows[$i]['x'] = $value;
$_rows[$i]['y'] = $value;
$i++;
}
}
This results in the following response:
array(48) {
[0]=>
array(2) {
["x"]=>
string(7) "3283581"
["y"]=>
string(7) "3283581"
}
[1]=>
array(2) {
["x"]=>
string(10) "2013-10-16"
["y"]=>
string(10) "2013-10-16"
}
So it isn't okay yet.. it should say:
array(48) {
[0]=>
array(2) {
["x"]=>
string(7) "3283581"
["y"]=>
string(7) "2013-10-16"
}
[1]=>
array(2) {
["x"]=>
string(10) "1512116"
["y"]=>
string(10) "2013-10-17"
}
Can anyone tell me what I need to adjust in order to get the right output?
/////////////////////////////////
this is what's in $rows (a part of the output)
array(24) {
[0]=>
object(stdClass)#169 (2) {
["SUM(positive)"]=>
string(7) "3283581"
["DATE(stamp)"]=>
string(10) "2013-10-16"
}
[1]=>
object(stdClass)#160 (2) {
["SUM(positive)"]=>
string(7) "1512116"
["DATE(stamp)"]=>
string(10) "2013-10-17"
}
I think the first step here is to fix your output array from the Codeigniter model. Did you create:
$rows = $this->Website_model->getGraphDataPositives();
If so, you should be able to easily go into the function and change the output of the select statement.
Where you find "SUM(positive)" and "DATE(stamp)" in the function getGraphDataPositives(), change it to this (rough example, I don't know what the function looks like):
SUM(positive) AS x
DATE(stamp) AS y
Now you can just run it this way instead:
$rows = $this->Website_model->getGraphDataPositives();
$_rows = array();
foreach ($rows as $i => $row) {
foreach ($row as $column => $value) {
$_rows[$i][$column] = $value;
}
}
Also notice that I removed the $i = 0 and $i++ and replaced $key wit $i. Much easier that way.
Let me know if this helps.
EDIT: I accidentally kept the second $_rows[$i][$column] = $value; in there; that's not needed anymore. You only need one, and the way you have it set up its setting the same value to both entries.
EDIT 2: Just wanted to note that the above example may not be the best option, the best option would be to give more description aliases.
SUM(positive) AS positive
DATE(stamp) AS timestamp
Then set the values like this:
foreach ($rows as $i => $row) {
$_rows[$i]['x'] = $row->positive;
$_rows[$i]['y'] = $row->timestamp;
}
Either option will work, the first is just a little easier.
It would be easier if i knew the column names from SQL but here goes:
$rows = $this->Website_model->getGraphDataPositives();
$_rows = array();
foreach ($rows as $row) {
$_rows[] = array(
'x'=>$row['x-column-name-here'],
'y'=>$row['y-column-name-here']
);
}
foreach ($rows as $key => $row) {
// here $key is index, $row is the object
foreach ($row as $column => $value) {
// here $column will be "SUM(positive)" and the value will be 3283581
// for the first iteration. Since both are assigned $value
// $_rows[$i]['x'] and $_rows[$i]['y'] will be identical
$_rows[$i]['x'] = $value;
$_rows[$i]['y'] = $value;
$i++;
}
}
If you just use the object columns as you defined you should be ok:
foreach ($rows as $row) {
$_rows[$i]['x'] = $row->{'SUM(positive)'};
$_rows[$i]['y'] = $row->{'DATE(stamp)'};
}
You're also not using $key so might as well get rid of that as well.
Your example is kind of basic but I think this should solve its issues:
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
$_rows[$key][$column%2==0?'x':'y'] = $value;
}
}
Provided you're using PDO::FETCH_NUM, ie your $rows are numerically indexed.

Foreach loop working, but outputting "invalid argument"?

I hope to give enough information here, but I am confused as to why the foreach loop works, it gets each data and outputs it in an li but I am getting an invalid argument error?
Here is the result of the var_dump
array(1) { ["questions"]=>
array(2) { ["title"]=> string(5) "Keanu" [1]=>
array(1) { ["questionlist"]=> array(2) { [0]=>
array(1) {
["a-question"]=> string(1) "1" } [1]=> array(1) {
["a-question"]=> string(5) "civil" } } } } }
Here is my foreach statement
foreach($questions['questions'] as $key => $value){
foreach($value['questionlist'] as $key => $subquestion){ //line 119
echo '<li>'.$subquestion['a-question'].'</li>';
}
}
$questions is a variable used to get the data from the database like this.
$questions = $wpdb->get_row("SELECT * FROM $table_name ORDER BY id DESC LIMIT 1" , ARRAY_A);
The data comes from ajax, I modify the ajax $_POST like this before sending to the database.
// Add modifications
$questions['questions'] = $_POST['questions']['data'];
// DB data
$name = $wpdb->escape($questions['questions']['title']);
$data = $wpdb->escape(json_encode($questions));
Screenshot:
I am not sure why I am getting the invalid argument, I suspect its because the array may not be formatted properly, if you need any more information let me know.
A Solution: Thanks to #didierc
I used his code and modified it a bit to display my data in a loop, basically all I did was add another foreach.
foreach($questions['questions'] as $key => $value){
if(is_array($value) && isset($value[ 'questionlist'])){
foreach($value as $key => $subquestion){ //line 119
foreach ($subquestion as $key => $value){
// This loops all the ['a-question'] data
echo '<li>''.$value['a-question'].''</li>';
}
}
}
}
Try this:
foreach ($questions['questions'] as $key => $value) {
if (is_array($value) && isset($value[ 'questionlist'])) {
foreach ($value['questionlist'] as $subnum => $subquestion) {
foreach ($subquestion as $qtitle => $qanswer) {
With variable names hopefully explicit enough. That should get you started.
NB: The data is probably easier to understand when formatted as below:
array(1) {
["questions"]=> array(2) {
["title"] => string(5) "Keanu"
[1] => array(1) {
["questionlist"]=> array(2) {
[0]=> array(1) {
["a-question"]=> string(1) "1"
}
[1]=> array(1) {
["a-question"]=> string(5) "civil"
}
}
}
}
}

Categories