arrays in foreach in yii 1 - php

I have following code in my controller:
$data= Yii::app()->db->createCommand()
->select('region_id')
->from('user_rights')
->where('user_group_id='.$findRegion['user_group_id'])
->queryAll();
foreach($data as $key=>$value){
$array_o[$key] = $value;
}
var_dump($array_o); returns following value:
array(2) { [0]=> array(1) { ["region_id"]=> string(4) "1703" } [1]=> array(1) { ["region_id"]=> string(4) "1706" } }
But, I need to get similar to following value:
array(2) { [0]=> string(4) "1703" [1]=> string(4) "1706" }.
How can I do it?

Just set the proper value right from the beginning:
foreach ($data as $key => $value){
$array_o[$key] = $value['region_id'];
}

You can use queryColumn() method
So it is just enough set statment
$data= Yii::app()->db->createCommand()
->select('region_id')
->from('user_rights')
->where('user_group_id='.$findRegion['user_group_id'])
->queryColumn();
and delete your foreach statment.

Try to make it like this
foreach($data as $key=>$value){
$array_o[$key] = $value['region_id'];
}

In your foreach do this:
$array_o[$key] = $value['region_id'];

Related

PHP Arrays - Merge two arrays where a value is added together

I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;

build json data from php object

I want to buld a Json object to feed my graphs. I have got the following code to change my PHP object.
$rows = $this->Website_model->getGraphData();
$_rows = array();
$i = 0;
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
$_rows[$i][] = $value;
}
$i++;
}
$rows = $_rows;
echo json_encode(array("sEcho" => intval($sEcho), "data" => $rows));
die();
My current ouput looks like this:
array(24) {
[0]=>
array(3) {
[0]=>
string(7) "3283581"
[1]=>
string(10) "2013-10-16"
}
It should look something like this:
{"y":15,"x":"2012-11-19"},{"y":18,"x":"2012-11-19"} etc etc
How can I add the Y and X to my data and take care i will get the right output to feed my graph?
/////////////////////////////////////////////////////
I tried the following:
Now i'm using the following code:
$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"
}
This would create an array like you wish :
$rows = $this->Website_model->getGraphData();
$_rows = array();
$i = 0;
foreach ($rows as $key => $row) {
$_rows[$i]['y'] = $rows[0];
$_rows[$i]['x'] = $rows[1];
$i++;
}
Your example data is not correct. You have array(3), but you show only 2 elements. Also in the output data you have 3283581 and the y values are 15 and 18. So there is no way I can guess how to convert those values.

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"
}
}
}
}
}

PHP sequential foreach

Guys i've got an array thats like this:
array(3) {
[2]=>
array(1) {
["name"]=>
array(2) {
[0]=>
string(13) "row1"
[1]=>
string(13) "row3"
}
}
[5]=>
array(1) {
["name"]=>
array(2) {
[0]=>
string(15) "row1"
[1]=>
string(15) "row3"
}
}
[3]=>
array(1) {
["name"]=>
array(2) {
[0]=>
string(13) "row1"
[1]=>
string(13) "row3"
}
}
What i want to achieve is make foreach loop the 0 elements (row1) and then loop through 1 (row3) and go on like this. Is there a way to do that?
You could try to rebuild the array:
$rows = array();
foreach($array as $subarray)
foreach($subarray as $key => $value)
$rows[$key][] = $value;
At this point al the same subelements from the array are together in a new array, and now you can easy loop over a subelement:
foreach($rows as $key => $value)
echo 'processing row: ' . $key ' with value ' . $value;
I found a different approach to this problem, the JvdBeg solution is working wonderful, but if someone is stuck in a similar situations, this is how i did it:
$key = key($arr);
$keys = array_keys($arr);
for ($i=0;$i<sizeof($arr[$key]['index']);$i++) {
for($k=0;$k<sizeof($arr);$k++) {
$key = $keys[$k];
echo "\n";
}
}

Categories