I have the following code:
var_dump($cursor);
foreach($cursor as $obj) {
echo "<div class='item' id='" . $obj['_id'] . "'>";
echo "<span class='listnick'>" . $obj['nick'] . "</span>";
echo "</div>";
}
The result of var_dump is the following:
array(2) {
[0]=>
&array(9) {
["_id"]=>
object(MongoId)#9 (1) {
["$id"]=>
string(24) "50af8dcd9cc231534400000c"
}
["nick"]=>
string(6) "safari"
}
[1]=>
array(9) {
["_id"]=>
object(MongoId)#8 (1) {
["$id"]=>
string(24) "50af8dca9cc2315644000009"
}
["nick"]=>
string(6) "chrome"
}
}
so obviously the foreach should print out "safari" and "chrome", but the problem is really weird:
Sometimes it returns "safari" twice and omits "chrome", and viceversa for the other client. I tried putting the var_dump and the foreach loop near to be sure they are the SAME and there are no changes in the object between the two commands, but really I got no idea what's going on.
Any help? Thanks in advance.
Notice how safari is a reference to an array: &array.
This might result from having a foreach where $obj is a reference:
foreach($cursor as &$obj) {
..
}
//unset($obj);
In PHP, the scope of $obj does not end with execution of the loop, so you should do an unset whenever you looped using a reference.
This might also result from using the reference assignment somewhere:
$cursor[] =& $safari;
This are 2 difference codes ... One is using & reference which would modify the array output and the other is not
array(2) {
[0]=>
&array(9) {
^----------------------------- Reference sign
["_id"]=>
object(MongoId)#9 (1) {
["$id"]=>
string(24) "50af8dcd9cc231534400000c"
}
["nick"]=>
string(6) "safari"
}
Topical example of what happened
$a = $b = array(array("_id" => new MongoId(),"nick" => "chrome"));
foreach ( $a as $k => &$v )
$k == "nick" and $v['nick'] = "Safari";
foreach ( $b as $k => $v )
$k == "nick" and $v['nick'] = "Safari";
var_dump($a);
var_dump($b);
Output
array (size=1)
0 =>
&array (size=2)
'_id' =>
object(MongoId)[1]
public '$id' => string '50af93a2a5d4ff5015000011' (length=24)
'nick' => string 'Safari' (length=6) <------ changed
array (size=1)
0 =>
array (size=2)
'_id' =>
object(MongoId)[2]
public '$id' => string '50af93a2a5d4ff5015000012' (length=24)
'nick' => string 'chrome' (length=6) <------- not changed
Can you see that one if the Nick is modified not the two
Related
Ive researched this but im coming up blank, Im generating an array of tests from a database like so:
$descriptions = array();
foreach ($tests as $value) {
array_push($descriptions, ['name' => $value['name']]);
}
I'm getting the desired out put but i'm getting a Multidimensional array of an array with '[64]' arrays inside '$descriptions', I need to convert this array so I get the following output:
'name' => $value1, 'name' => $value2, etc etc for all results,
I've tried implode, array_merge etc but the closest I've got is a flat array with only my last test: [name] => Zika can anyone point me in the right direction? cheers
You can't have duplicate array keys. But you can pass an array in like so:
<?php
$descriptions = array();
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions[] = array('name' => $value);
}
var_dump($descriptions);
Which gives you :
array(6) { [0]=> array(1) { ["name"]=> string(4) "Zika" } [1]=> array(1) { ["name"]=> string(4) "SARS" } [2]=> array(1) { ["name"]=> string(4) "AIDS" } [3]=> array(1) { ["name"]=> string(15) "Mad Cow Disease" } [4]=> array(1) { ["name"]=> string(8) "Bird Flu" } [5]=> array(1) { ["name"]=> string(16) "Zombie Infection" } }
So you could foreach ($descriptions as $desc) and echo $desc['name']';
Have a look here: https://3v4l.org/pWSC6
If you just want a string, try this:
<?php
$descriptions = '';
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions .= 'name => '.$value.', ';
}
$descriptions = substr($descriptions, 0, -2); // lose the last comma
echo $descriptions;
Which will output:
name => Zika, name => SARS, name => AIDS, name => Mad Cow Disease, name => Bird Flu, name => Zombie Infection
See it here https://3v4l.org/OFGF4
I have seen strange behavior that I don't quite get. I do the following:
$array = [
'a' => [
'a1' => [
'a11' => 1,
'a12' => 2
],
'a2' => [
'a21' => 3,
'a22' => 4
],
],
'b' => [
'b1' => [
'b11' => 1,
'b12' => 2
],
'b2' => [
'b21' => 3,
'b22' => 4
],
],
];
foreach ($array as $strLevel1 => &$arrLevel1)
{
foreach ($arrLevel1 as $strLevel2 => &$arrLevel2)
{
foreach ($arrLevel2 as $strLevel3 => &$varLevel3)
{
$varLevel3 = 0;
}
}
}
echo '<pre>';
var_dump($array);
echo '</pre>';
foreach ($array as $strLevel1 => $arrLevel1)
{
}
echo '<pre>';
var_dump($array);
echo '</pre>';
The result is as follows:
array(2) {
["a"]=>
array(2) {
["a1"]=>
array(2) {
["a11"]=>
int(0)
["a12"]=>
int(0)
}
["a2"]=>
array(2) {
["a21"]=>
int(0)
["a22"]=>
int(0)
}
}
["b"]=>
&array(2) {
["b1"]=>
array(2) {
["b11"]=>
int(0)
["b12"]=>
int(0)
}
["b2"]=>
&array(2) {
["b21"]=>
int(0)
["b22"]=>
&int(0)
}
}
}
array(2) {
["a"]=>
array(2) {
["a1"]=>
array(2) {
["a11"]=>
int(0)
["a12"]=>
int(0)
}
["a2"]=>
array(2) {
["a21"]=>
int(0)
["a22"]=>
int(0)
}
}
["b"]=>
&array(2) {
["a1"]=>
array(2) {
["a11"]=>
int(0)
["a12"]=>
int(0)
}
["a2"]=>
array(2) {
["a21"]=>
int(0)
["a22"]=>
int(0)
}
}
}
As you can see, in the first output everything is ok. But in the second one, the b-named branch of the array is replaced by the a-named branch. This is because of the referencing I did. If I put a "&" before $arrLevel1 in the last loop, it works again.
Why is that? Am I doing something wrong with the references? Or should I don't use them at all and do array manipulation only fully qualified without any reference?
Thanks in advance.
Maybe you should unset the reference to $arrLevel1 after your loop, till you reused the var for the second loop.
foreach ($array as $strLevel1 => &$arrLevel1)
{
foreach ($arrLevel1 as $strLevel2 => &$arrLevel2)
{
foreach ($arrLevel2 as $strLevel3 => &$varLevel3)
{
$varLevel3 = 0;
}
}
}
// remove reference
unset($arrLevel1);
echo '<pre>';
var_dump($array);
echo '</pre>';
foreach ($array as $strLevel1 => $arrLevel1)
{
}
echo '<pre>';
var_dump($array);
echo '</pre>';
A way to come around unset is to use unique names for your loop variables or - if you want to loop over the same array again - just also use an reference loop var.
foreach ($array as $strLevel1 => &$arrLevel1)
{
foreach ($arrLevel1 as $strLevel2 => &$arrLevel2)
{
foreach ($arrLevel2 as $strLevel3 => &$varLevel3)
{
$varLevel3 = 0;
}
}
}
// also use a reference
foreach ($array as $strLevel1 => &$arrLevel1)
{
}
Most of the time, it might be simplier to just don't use references or move the loop in an "atomic" function which just does the manipulation and returns the result.
I have an array like this:
array(5) {
[0]=> array(1) { ["go-out"]=> string(7) "#0d4b77" }
[1]=> array(1) { ["cycling"]=> string(7) "#1472b7" }
[2]=> array(1) { ["diving"]=> string(7) "#1e73be" }
[3]=> array(1) { ["exploring"]=> string(7) "#062338" }
[4]=> array(1) { ["eating"]=> string(7) "#f79e1b" }
}
Let's say I have the first value like 'cycling', so how can I find the '#147217' value?
I have been trying a lot of combinations of
foreach ( $array as $key => list($key1 ,$val)) {
if ($key1 === $id) {
return $val;
}
}
But no luck.
Ideas?
You can use array_column -
array_column($your_array, 'cycling');
DEMO
You should also add the checks for key's existence.
you may still make one loop
$id = "cycling";
foreach($array as $val)
if(isset($val[$id])) echo $val[$id];
Demo on Evail.in
I have reformated tour code, try this, that works:
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$id = "cycling";
foreach ($array as $key => $entry) {
if ($entry[$id]) {
echo $entry[$id];
}
}
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$search = "cycling";
foreach ($array as $key => $entry)
if (isset($entry[$search]))
echo $entry[$search];
That works.
Nice day.
I have an array from json_decode. And i want to reformat it.
this is my array format.
["Schedule"]=>array(1) {
["Origin"]=>
string(3) "LAX"
["Destination"]=>
string(2) "CGK"
["DateMarket"]=>
array(2) {
["DepartDate"]=>
string(19) "2015-02-01T00:00:00"
["Journeys"]=>
array(6) {
[0]=>
array(6) {
[0]=>
string(2) "3210"
[1]=>
string(14) "Plane Name"
[2]=>
string(8) "20150201"
[3]=>
string(8) "20150201"
[4]=>
string(4) "0815"
[5]=>
string(4) "1524"
}
}
}
And i want change the indexed array to associative with foreach function.
And here is my PHP code
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value->Name= $value[1];
}
But i got an error "Attempt to assign property of non-object on line xXx..
My Question is, how to insert a new associative array to indexed array like the example that i've provide.
UPDATE : I've tried this solution
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name']=$value[1];
}
But my array format still the same, no error.
In this line:
$value->Name= $value[1];
You expect $value to be both object ($value->Name) and array ($value[1]).
Change it to something like:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$response->Schedule['DateMarket']['Journeys'][$key]['Name'] = $value[1];
}
Or even better, without foreach:
$keys = array(
0 => 'Id',
1 => 'Name',
2 => 'DateStart',
3 => 'DateEnd',
4 => 'HourStart',
5 => 'HourEnd',
);
$values = $response->Schedule['DateMarket']['Journeys'];
$response->Schedule['DateMarket']['Journeys'] = array_combine( $keys , $values );
Array_combine makes an array using keys from one input and alues from the other.
Docs: http://php.net/manual/en/function.array-combine.php
Try this:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name'] = $value[1];
}
You want to create new array index, but try to create new object.
foreach ($response->Schedule['DateMarket']['Journeys'] as $key => $value) {
$value['Name'] = $value[1];
}
I have an array that I'm creating inside my PHP script, the var_dump function gives me this value :var_dump($arrayOfValues);
array(3) {
[0]=> array(2) {
[0]=> string(12) "BusinessName"
[1]=> string(13) "ITCompany"
}
[1]=> array(2) {
[0]=> string(7) "Address"
[1]=> string(58) "29 xxxxxx,Canada"
}
[2]=> array(2) {
[0]=> string(20) "PrimaryBusinessPhone"
[1]=> string(14) "(444) 111-1111"
}
[3]=> array(2) {
[0]=> string(13) "BusinessEmail"
[1]=> string(24) "xx#example.com"
}
}
I would like to access to the value of the "BusinessName" using key and not index so if I put : echo $arrayOfValue[0][1]; it gives me the BusinessName that is ITCompany but if I put
: echo $arrayOfValue['BusinessName'][1]; it gives nothing so how can I fix that please?
The array is initialized $arrayOfValue = array(); and then populated dynamically inside a for loop like that
$arrayOfValue[] = array($Label, $Value);
your array has this kind of data
$arrayOfPostsValue[] = array("BusinessName","ITCompany");
$arrayOfPostsValue[] = array("Address","29 xxxxxx,Canada");
$arrayOfPostsValue[] = array("PrimaryBusinessPhone","(444) 111-1111");
$arrayOfPostsValue[] = array("BusinessEmail","xx#example.com");
there is no array key in data So, you have to recreate your desire array
$newArrayOfPostsValue = array();
foreach ( $arrayOfPostsValue as $value ){
$newArrayOfPostsValue[$value[0]] = $value[1];
}
print_r($newArrayOfPostsValue);
and here is output
Array
(
[BusinessName] => ITCompany
[Address] => 29 xxxxxx,Canada
[PrimaryBusinessPhone] => (444) 111-1111
[BusinessEmail] => xx#example.com
)
As mentioned in the comment, change the structure of the array, it will be much easier to handle
$my_array = array(
array('Business Name' => 'It Company'),
array('Address' => 'My address')
);
Looking at the content of your array, I will restructure it as
$my_improved_array = array(
'BusinessName' => 'It Company',
'Address' => 'My Address',
);
This is how you can access,
echo $my_array[0]['BusinessName'] //prints 'It Company'
echo $my_array[1]['Address'] //prints 'My Address'
echo $my_improved_array['BusinessName'] // prints 'It Company'
Try like this and save array as key value pairs and then access the key:
foreach($arrayOfValues as $a)
$arr[$a[0]] = $a[1];
echo $arr['BusinessName'];
While creating that array build it with index as BusinessName
array (
0 => array(
'BusinessName'=> "ITCompany"
)
1 => array(1) (
'Address'=> "29 xxxxxx,Canada"
)
)
etc..
PHP Array example
$array = array();
$array['BusinessName'] = 'ITCompany';
$array['Address'] = '29 xxxxxx,Canada';
And so on... Now you can echo values with
echo $array['BusinessName'];
Also this works
$array = array('BusinessName' => 'ITCompany', 'Address' => '29 xxxxxx,Canada');
First of all, how are you building this array ? Maybe you can directly make a workable array.
Anyway, you can do something like this :
$oldArray = Array(
Array("BusinessName", "ITCompany"),
Array("Address", "29 xxxxxx,Canada"),
Array("PrimaryBusinessPhone", "(444) 111-1111"),
Array("BusinessEmail", "xx#example.com")
);
$newArray = Array();
foreach($oldArray as value) {
$newValue[$value[0]] = $value[1];
}
/* Now, it's equal to
$newArray = Array(
"BusinessName" => "ITCompany",
"Address" => "29 xxxxxx,Canada",
"PrimaryBusinessPhone" => "(444) 111-1111",
"BusinessEmail" => "xx#example.com"
);
*/