php Undefined index when I dont use a redundant if statement - php

I have a multidimensional array that I want to access and change one of the values from an integer to a string using a helper function. The code below works but if I remove the if statement which I dont really need it gives me a Undefined index error on the helper code
$stories = multidimensional array in this format
array(1) {
[0]=> array(4)
{
["code"]=> string(1) "2"
["user_name"]=> string(4) "Dave"
["name"]=> string(11) "project one"
["sample_id"]=> string(1) "2"
}
}
to access the array I am using
foreach($stories as $key => $subarray) {
if(array_key_exists('code', $subarray)){
//if($stories[$key]['code'] > 0){
$stories[$key]['code'] = task_priority_text($stories[$key]['code']);
//};
}
}
Commenting the code in this way throws the error while uncommenting gives a clean result.
Here is the helper function which I have used elsewhere and works well
if ( ! function_exists('task_priority_text'))
{
function task_priority_text($priority = FALSE)
{
$options = array('0' => 'Urgent', '1' => 'High', '2' => 'Medium', '3' => 'Low', '4' => 'Minimal');
if($priority !== FALSE)
return $options[$priority];
else
return $options;
}
}
How do I get ride of this if statement?
EDIT
here is the error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: Medium
Filename: helpers/tasks_helper.php
Line Number: 70
line 70 of the helper is
return $options[$priority];

You are looping over each item in the array multiple times. The 'outer' loop runs once for every item in the array, then the 'inner' loop (which someone else pointed out is redundant) runs again for every item in the $subarray variable.
foreach($stories as $key => $subarray) {
foreach($subarray as $subkey => $subsubarray) {
if(array_key_exists('code', $subarray)){
//if($stories[$key]['code'] > 0){
$stories[$key]['code'] = task_priority_text($stories[$key]['code']);
//};
}
}
}
This would be a better way of doing it:
foreach($stories as $story)
{
$story['code'] = task_priority_text($story['code']);
}

Related

Getting unexpected response from Laravel factory() causing Segmentation Fault (Core Dumped)

A Laravel factory() function inside a factory()->create()->each() is giving a very unexpected result. The function is returning a huge array full of strings and sub-arrays, when var_dumping it inside the console I have to ctrl+c to stop it from rendering the result else it keeps on running (haven't seen the end of the array). When executing php artisan DB:seed I'll the following result: Segmentation fault (Core dumped).
The content inside the array looks like data from the Faker library.
Does anyone has an idea of where this can possibly come from?
I have minimized my code down to only the factory for the Model I want to insert in my DB. This ofcourse still is giving me the same result.
I have var_dumped the class name from the object returned, the object returned is from the class "Illuminate\Database\Eloquent\FactoryBuilder". As expected.
Inside the SubscriptionFactory.php file I have commented out everything inside the $factory->define() function.
Code
The code below is giving me the never ending array.
factory(App\SubscriptionGroup::class, 3)
->create()
->each(function ($subscriptionGroup)
{
$test = factory(App\Subscription::class);
var_dump($test);
});
The code below is my SubscriptionFactory php file.
use Faker\Generator as Faker;
$factory->define(App\Subscription::class, function (Faker $faker)
{
$minAge = null;
if (rand(0, 100) > 75) {
$minAge = $faker->randomElement([12, 16, 18]);
}
$maxAge = null;
if (rand(0, 100) > 75) {
$maxAge = $faker->randomElement([21, 35, 50]);
}
$duration = 1;
if (rand(0, 100) > 25) {
$duration = $faker->randomElement([1, 6, 12, 24]);
}
$paidByMember = null;
if (rand(0, 100) > 90) {
$paidByMember = true;
} elseif (rand(0, 100) > 90) {
$paidByMember = false;
}
$tokenPeriod = \App\TokenPeriod::find(rand(1, 7));
$directDebitPeriod = \App\DirectDebitPeriod::find(rand(1, 3));
$unlimitedAccess = $faker->boolean(10);
$periodicTokens = 0;
$transferableTokenPeriod = 0;
if ( ! $unlimitedAccess) {
$periodicTokens = $faker->randomElement([1, 2, 4]);
$transferableTokenPeriod = rand(0, 4);
}
$name = implode(' ', $faker->words(rand(1, 2)));
return [
'status' => 'published',
'name' => $name,
'min_age' => $minAge,
'max_age' => $maxAge,
'membership_duration' => $duration,
'membership_duration_in' => 'months',
'available_date' => \Carbon\Carbon::now(),
'withdraw_date' => null,
'visibility_order' => 1,
'paid_by_member' => $paidByMember,
'unlimited_access' => $unlimitedAccess,
'periodic_tokens' => $periodicTokens,
'transferable_token_period' => $transferableTokenPeriod,
'check_in_access_type_id' => 1,
'token_period_id' => $tokenPeriod->id,
'direct_debit_period_id' => $directDebitPeriod->id
];
});
Result
The SubscriptionGroup factory is running as expected and fills the database accordingly. But the Subscription factory is giving the wrong result. See the piece of the resulting array below.
...
["de schuitjes"]=>
array(1) {
[0]=>
string(3) "van"
}
["schuitjes van"]=>
array(1) {
[0]=>
string(3) "den"
}
["den ponton-steiger"]=>
array(1) {
[0]=>
string(3) "bij"
}
["ponton-steiger bij"]=>
array(1) {
[0]=>
string(9) "Nijmegen."
}
["bij Nijmegen."]=>
array(1) {
[0]=>
string(2) "En"
}
["Nijmegen. En"]=>
array(1) {
[0]=>
string(2) "nu"
}
["nu spraken"]=>
array(1) {
[0]=>
string(2) "ze"
}
["ze over"]=>
array(2) {
[0]=>
string(3) "z'n"
[1]=>
string(2) "'t"
}
...
EDIT
The code below also seems to cause the Segmentation fault (core dumped) error. So it seems the error doesn't come from factory(App\Subscription::class), but rather the subscriptions() relation inside SubscriptionGroup. Which makes it even stranger because that's just a simple hasMany relationship.
factory(App\SubscriptionGroup::class)
->create()
->each(function ($subscriptionGroup)
{
$subscriptionGroup->subscriptions();
});
The subscriptions() relation inside the SubscriptionGroup class:
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function subscriptions()
{
return $this->hasMany('App\Subscription');
}
I have found the answer to my own problem.
For certain models I had created an abstract class with a $scope attribute. The attribute had a default value 'public'. After removing the default value from this attribute everything worked.
I've moved the default value for this attribute to the constructor method.

Add array in array of arrays

I have a $_SESSION index called "items".
Just like this:
$_SESSION['items'];
When user click to add item I check if $_SESSION['items'] exists. If exists, then insert the item, if not, create and insert. Ok.
So I coded this solution:
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
if(isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = $newItem;
}
Ok.
The problem is:
If the "else" occurs, the $newItem array is pushed into $_SESSION['items'] with this structure:
{
0: {
id: "1",
ref: "0001",
}
}
Exactly as I was expecting.
But if the "if" statement occurs, my $_SESSION['item'] looses the new indexes and I get a structure like this:
{
0: {
id: "1",
ref: "0001",
},
id: "2",
ref: "0001",
}
As you can see, the new item is not set as array...
If I add more itens, the issue affects only the last item added...
What I am doing wrong?
Change your code to the following:
if (isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = [];
array_push($_SESSION['items'], $newItem);
}
Now, all the $newItems will be pushed in to an actual array.
Output
array(1) {
["items"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "id"
["ref"]=>
string(3) "ref"
}
[1]=>
array(2) {
["id"]=>
string(4) "id-2"
["ref"]=>
string(5) "ref-2"
}
}
}
Live Example
Repl - Dummy data used
Your array_push here seems to be problem, because when you are pushing the array in $_SESSION[‘items’] it takes $newItem array elements and pushes them in the $_SESSION[‘items’]
If you can do as below then it should work
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
$_SESSION['items'][]= $newItem;

How to access an element in an array in PHP

Hi I am trying to access a property of an object from an array but seems to not getting it correctly. I have an array of objects that is posted in PHP.
$classrooms = $_POST->client->classrooms
when I do a var_dump($classrooms) I get the structure like below:
array(1) {
[0]=>
array(2) {
[0]=>
object(stdClass)#5 (4) {
["classroomid"]=>
int(2)
["classroom"]=>
string(7) "Grade 1"
}
[1]=>
object(stdClass)#6 (4) {
["classroomid"]=>
int(4)
["classroom"]=>
string(9) "Grade 2"
}
}
}
I am trying to access "classroom" property using following code in PHP but it does not output anything.
foreach($classroom as $item)
{
echo $item['classroom'];
}
But if try like this (by hardcoding index) it gives me correct name of classrooms but I cannot pass the index as I do not know how many will be in the array.
foreach($classroom as $item)
{
echo $item[0]['classroom'];
}
Thank you for reading this.
Try like this,
$lists = [];
foreach($classroom as $item)
{
foreach($item as $k => $v){
$lists[] = $v->classroom; // or $v->classroom;
}
}
print_r($lists);
For stdClass object you have to use "->" to get the key value.
foreach($classroom as $subarray) {
foreach($subarray as $item) {
echo $item->classroom;
}
}
If you use $item['classroom'] it will throw an error:
PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array.

php : manually create a array

NEW Update
How will you write a array which output will be like this:
Array(1) { [0]=> object(stdClass)#29 (15) { ["cals"]=> string(11) "1545.616024" } }
OLD UPDATE
I am trying to manually insert value in a array if My db is resulting 0 results.
I am trying to create a manually a array which stores value as this model function stores
public function fetch_LifeStyeActivity_byid($activityDate, $uid) {
----
----
$query = $this->db->order_by('calorie_activity.ordering', 'ASC')->get_where('calorie_activity', array('creater_id' => $uid,'activity_date' => $activityDate, 'parent_id =' => '625'));
$data = array();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
I am creating it like this from my controller like this
$data["lifeStyle_activity_query"] = array(
"cals" => "6"
);
$this->load->view('weight_lose/activities', $data);
& in view page while retrieving i am getting exception
foreach ($lifeStyle_activity_query as $row) {
echo $row->cals;
}
Exception getting as:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Note: I only need help on modifying controller logic(please do not tell to change the view page code)
Your error simply comes from the fact that you've an array and try to use it as an object. You could just cast your array into an object so it can be used as such in your view.
$data["lifeStyle_activity_query"] = array(
"cals" => "6"
);
$data["lifeStyle_activity_query"] = (object) $data["lifeStyle_activity_query"];
echo $data["lifeStyle_activity_query"]->cals; // -> 6
Edit for your update :
$val['cals'] = '1545.616024';
$arr[0] = (object) $val;

Can't retrieve associative array index in php

I have an array that looks like the following:
array(3) { [0]=> array(1)
{
["habitacionales"]=> array(1)
{ ["Azcapotzalco"]=> string(1) "3" } }
[1]=> array(1) { ["comerciales"]=> array(0) { } }
[2]=> array(1) { ["industriales"]=> array(0) { } }
}
And I need to check if the array belongs to the type "habitacionales", or "comerciales", etc. But no matter what I do, I keep getting the notice "Undefined index: habitacionales". Could someone point out how to access that index?
I am using cakephp, and I am setting the variables in the controller like this:
$zonasHab = $this->PropiedadesHabitacionale->BasicosPropiedadesHabitacionale->find('list', array('fields'=>array('Zona', 'propiedad_habitacional_id')));
then I do:
$this->set('Zonas', array_unique($linksZonas, SORT_REGULAR));
And finally in the view I do:
foreach ($Zonas as $zona) {
foreach($zona as $zone) {
foreach(array_flip($zone) as $link) {
echo '<li class="dropdownheader">'.$link;
}
var_dump($zone['habitacionales']);
}/*
if($zona['habitacionales']!=null)
foreach(array_flip($zone) as $vinculo) {
echo '<li>'.$this->Html- >link($vinculo, array('controller'=>'propiedadeshabitacionales', 'action'=>'ver', $vinculo)).'</li>';
}
*/
echo '</li>';
}
Just to point out, the wierd thing is that if I do var_dump($zona['habitacionales']); inside the outer foreach, I get the correct value: array(1) { ["Azcapotzalco"]=> string(1) "3" } but I still get the notice appearing telling me it's an undefined index, and I can't use that same syntax ($zona['habitacionales'] for a condition or anything else.
Assuming $Zonas is that array above, try:
foreach($zona as $zone) {
foreach(array_flip($zone) as $link) {
echo '<li class="dropdownheader">'.$link;
}
var_dump($zone);
habitacionales is the key, if you want to access that then use:
foreach($zona as $key => $zone) {
And $key should be set to habitacionales.

Categories