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);
Related
I'm having an issue when I dump the array below. This dumps several arrays. Some are 2 some are 3, which complicates it even more. Basically what I want I put below. I have tried array_push, array_combine, array_merge, several different ways including $array[$param] = $insertValue and I'm stuck. I am open to creating a brand new array too.
Please note not all arrays are counts of 3 but always return at least 1.
Original array:
array(3) {
[0]=>
array(2) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
}
[1]=>
array(2) {
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
}
[2]=>
array(2) {
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
Array desired:
array(3) {
[0]=>
array(6) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
try this code:
$NewArray = array();
foreach($OriginalArray as $value) {
$NewArray[] = array_merge($value,$NewArray);
}
or you can use array_merge_recursive
let $result = [];
foreach ($yourarray as $key => $value) {
$result = $value;
}
var_dump($result);
Here you go: How to Flatten a Multidimensional Array? – Barmar 23 mins ago
function flatten($array)
{
return array_reduce($array, function($acc, $item){
return array_merge($acc, is_array($item) ? flatten($item) : [$item]);
}, []);
}
// loop the individual fields
for ($i=0; $i<count($row_data); $i++) {
$newArray = flatten([$i => $response_row]);
}
Try something like this:
function flatten(array $array) : array
{
$newArray = [];
foreach ($array as $subArray) {
foreach ($subArray as $key => $value) {
$newArray[$key] = $value;
}
}
return $newArray;
}
I'm using
$data=json_decode($response,true)
the output is
array(3)
{
["instrument"]=> string(7) "EUR_USD" ["granularity"]=> string(1) "D" ["candles"]=> array(10)
{
[0]=> array(7)
{
["time"]=> string(27) "2016-09-26T21:00:00.000000Z" ["openMid"]=> float(1.125495) ["highMid"]=> float(1.1259) ["lowMid"]=> float(1.119125) ["closeMid"]=> float(1.121605) ["volume"]=> int(17059) ["complete"]=> bool(true)
}
[1]=> array(7)
{
["time"]=> string(27) "2016-09-27T21:00:00.000000Z" ["openMid"]=> float(1.1218) ["highMid"]=> float(1.12369) ["lowMid"]=> float(1.118215) ["closeMid"]=> float(1.12171) ["volume"]=> int(17915) ["complete"]=> bool(true)
}
}
}
I want to create two arrays with the values openMid and closeMid for example:
$open=array(1.125495,1.1218)
$close=array(1.121655,1.12171)
I have to develop the foreach code in order to achieve that.
Anyone can help me? Thanks
Check out the solution below:
$open= []; //Declare empty array to hold openMid values
$close= []; //Declare empty array to hold closeMid values
#Loop through $array
foreach ($array as $key => $value) {
#If any of the value is an array
if (is_array($value)) {
$arr= $value; //Store the array
}
}
//Loop through the second array
foreach ($arr as $val) {
//If the value is of index openMid
if ($val->openMid) {
$open[]= $val->openMid; //Push into the $open array holder
}
//If the value is of index closeMid
if ($val->closeMid) {
$close[]= $val->closeMid; //Push into the $close array holder
}
}
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'];
}
}
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.
I try to read some keys of an array like
array(3) {
["poste5:"]=> array(3) { [0]=> string(7) "APPLE:" [1]=> string(5)
"demo1" [2]=> string(5) "demo2" }
["services:"]=> array(4) { [0]=> string(9) "orange" [1]=>
string(5) "demo3" [2]=> string(5) "demo4" [3]=> string(5) "demo1" }
["essai:"]=> array(2) { [0]=> string(6) "sd" } }
I try to read this name : poste5 , services , essai
If i use :
foreach ($this->aliasRead as $key => $value){
echo array_keys($this->aliasRead[$key]);
}
I have : Array()
But if i use :
foreach (array_keys($this->aliasRead) as $key => $value2) {
echo $value2;
}
I have poste5 , services , essai
I try to use with this loop foreach ($this->aliasRead as $key => $value){
because i have another traitment after.
How to collect this key of my first loop in this loop foreach ($this->aliasRead as $key => $value){ ?
You already have what you want here:
foreach ($this->aliasRead as $key => $value){
echo $key; // key of the value in the array
print_r($value); // value of $this->aliasRead[$key] which in turn is another array
}
Edit: The reason your second loop works is because of this: array_keys($this->aliasRead[$key]) returns a new array containing the keys of the old array as its values. So $myNewArray = array_keys($this->aliasRead[$key]) is the same as $myNewArray = array('poste5','services','essai'). So, when you loop over this new array like this:
foreach ($myNewArray as $key => $value2) {
echo $value2;
}
$value2 contains your values, which are the keys of your first array, and $key will be 0, 1 and 2 after each step through the loop.
Try this,
$keys = array_keys($this->aliasRead);
print_r($keys);
Or
$keys = array();
foreach ($this->aliasRead as $key => $value){
$keys[] = $key;
}
It's because you're trying to echo an array. This will always give you the string "Array". If you want to see the array's contents, try
var_dump(array_keys($this->aliasRead[$key]));
By the way, in the foreach statement you posted, $this->aliasRead[$key] will be the equal to $value. So this will work as well:
var_dump(array_keys($value));