$raw_data = array ('data' => array ('id' => 'foo'));
$fields = array ('id_source' => "data['id']");
foreach ($raw_data as $data) {
foreach ($fields as $key => $path) {
var_dump ($data['id']);
var_dump ($$path);
}
}
The first var_dump gives me the correct value of foo. However, the second one gives me Undefined variable: data['id']. Can anyone tell me why that would be the case, especially since the first var_dump worked confirming the variable $data['id'] is set.
I realized this example is basic and I could just do $data[$key] and change $fields = array ('id_source' => 'id'); but I want to be able to go deeper into the multidimensional arrays when needed. That is why I'm trying to do my original approach.
Related
I am using unset to remove the particular object from the array with my conditions. But after unset, I am getting an object rather than an array. I tried to use array_values to rearrange the index, but it's not working for me. Please help me to resolve this issue. Below is my code:
$empId = '100'; //just for example.
foreach($jsonData['data'] => $key as $value){
if($value['emp_id'] == $empId){
unset($jsonData['data][$key]);
}
}
after loop code//
return $jsonData;
after unset data, it gives me an object. I tried with array_values, array_merge but it's not working for me.
I tried to replace array_splice with unset, but it's not removing data.
You have at least 2 serious syntax errors in your code.
This is what it should look like:
<?php
// Some dummy data
$empId = '100';
$jsonData = [];
$jsonData['data'] = [
'key' => ['emp_id' => 'value'],
'key2' => ['emp_id' => '100']
];
// Fixed foreach loop
foreach($jsonData['data'] as $key => $value) {
if ( $value['emp_id'] == $empId ) {
unset( $jsonData['data'][ $key ] );
}
}
print_r($jsonData);
key emp_id is as string, not as index.
your code has unset emp_id.
alternatively, you may use array_map function and then use array_values to reindex your array.
In my project i'm split an array index value based on regex value. but when i want merge all array together the merge function doesn't merge.
Here is my code sample.
$testarray=array();
$merge_array=array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
print_r(array_merge($merge_array,$testarray));
}
The print_r show this result.
Array ( [0] => Admin [1] => Manager ) Array ( [0] => User [1] => Test )
You just merge arrays, but don't assign results to any variable, proper code is:
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
// here you add $testarray values to
// `$merge_array` on each iteration
$merge_array = array_merge($merge_array,$testarray);
}
// print result array after loop
print_r($merge_array);
The Laravel framework has nothing to do with your issue. You're using PHP's standard functions.
The array_merge function doesn't modify the array you provide to it but provides the resulting array as its output. So you should assign array_merge's result to $merge_array.
Please try the following code:
$testarray = array();
$merge_array = array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray = preg_split("/[##%$|:\s,]+/",$value);
}
$merge_array = array_merge($merge_array, $testarray);
}
print_r($merge_array);
You seem to think wrong.
print_r(array_merge($merge_array,$testarray));
The above line is in "foreach" loop.
In that case, to get a merged result, you should do like the followings;
$merge_array = array_merge($merge_array,$testarray)
In your code, $merge_array remains empty, so you see the current result.
I have the following function which gets some data from DB table.
Now I realize this question must have been asked many times before but I refer you to this link which is the top result for problem Im having. Get the current key and value inside an array
When I call my function and do a var_dump(LoadBoxes()) all is well no problems, thus my function is working correctly as can be seen from the image below:
However when I try to get the array keys and values as pointed out by top linked question I get the following error:
Notice: Array to string conversion in
C:\xampp\htdocs\beta\xxxx\xxxx_letsGo.php on line 25 0 Array
So clearly I must be doing something wrong any help appreciated, code follows:
function LoadBoxes()
{
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$data[] = array(
'LowHeadline' => $box['lowHeadline'],
'MediumHeadline' => $box['mediumHeadline'],
'HighHeadline' => $box['highHeadline'],
'Low' => $box['BoxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $data;
//call function
$boxesInfo = LoadBoxes();
foreach($boxesInfo as $arrayKey => $info) {
echo $arrayKey.' '.$info;
}
Ive tried using LoadBoxes() function instead of assigning it to variable $boxesInfo[] inside foreach loop, same result. Ive pretty much tried everything to best of my knowledge any help appreciated.
Additional Info
It is only when I explicitly call the array key inside foreach() that I get result back like such:
foreach($boxesInfo as $arrayKey => $info) {
echo $boxesInfo['LowHeadline'] // returns LOW RISK
}
The problem is with [] in $boxesInfo[] = LoadBoxes(); Your function LoadBoxes() returns an array of boxinfo, and you assign that to an array. So the loop just sees an array with one element, which is itself another array. If you change the line to $boxesInfo = LoadBoxes(); you should get the expected result.
On second thought, loadBoxes() returns an array of boxes, which are themselves arrays, so you would need nested loops to get the info of all boxes:
foreach($boxesInfo as $box) {
foreach($box as $arrayKey => $info) {
echo $arrayKey.' '.$info;
}
}
Consider the structure for an associative array and a function which are composed by structure below:
$myCars = array("name" => "categories", "data" => array());
function getCategoriesData()
{
// data is gathered here
return $categoriesData
}
The “data” array should be populated with the return of the “getCategoriesData” function.
Considering that, how can I perform that action using a foreach loop?
Assuming that getCategoriesData() returns an Array, if you specifically need to use a foreach loop, we can write the code like this
$returnedArray = getCategoriesData();
foreach($returnedArray as $key => $value)
{
$myCars["data"][$key] = $value;
}
An even simpler approach would be this.
$mycars["data"] = getCategoriesData();
I have the following snippet of code that is creating the following array...
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Results in the follow array:
Array ( [0] => Array ( [cap_login] => master [cap_pword] => B-a411dc195b1f04e638565e5479b1880956011badb73361ca ) )
Basically I want to extract the cap_login and cap_pword values for testing. For some reason I can't get it!
I've tried this kind of thing:
echo $results[$cap_login];
but I get the error
Undefined variable: cap_login
Can someone put me right here?
Thanks.
cap_login is in an array within $results so you would have to do $results[0]['cap_login']
You would have to do the following:
echo $x[0]['cap_login'] . '<br />';
echo $x[0]['cap_pword'];
The reson $results[$cap_login] wont work is because there isn't a variable called $cap_login, there is a string called cap login. In addition, there isn't a key in $results called $cap_login. There is a value in $results called 'cap_login'