I am working on CakePHP 3.2
I have this function to find product types if exists
if ($product['product_type'] != null) {
$getProductType = $this->ProductTypes->find()
->where(['title LIKE' => '%'.$product['product_type'].'%'])
->first();
debug($product['product_type']); // this is not empty
debug($getProductType); // this shows 'id' => 1 in array
debug($getProductType->id); // this shows 1
if (!empty($getProductType)) {
$p->product_type_id = $getProductType->id; // line 11
$p->subcategory_id = $getProductType->subcategory_id;
$p->category_id = $getProductType->category_id;
return $this->saveNewBulkProduct($product, $p->category_id, $p->subcategory_id, $p->product_type_id);
}
}
But this is giving warning as
Creating default object from empty value on line 11
Edit 2 Output of print_r($getProductType)
App\Model\Entity\ProductType Object
(
[id] => 3
[category_id] => 1
....
)
I think no need to declare $p and not set property and its value in $p, you can pass values of $getProductType object as mentioned below.
if ($product['product_type'] != null) {
$getProductType = $this->ProductTypes->find()
->where(['title LIKE' => '%'.$product['product_type'].'%'])
->first();
debug($product['product_type']); // this is not empty
debug($getProductType); // this shows 'id' => 1 in array
debug($getProductType->id); // this shows 1
if (!empty($getProductType)) {
return $this->saveNewBulkProduct($product, $getProductType->category_id, $getProductType->subcategory_id, $getProductType->id);
}
}
you have to declare first $p = new stdClass(); on line 11
Related
i am fetching data from two tables as below :
$form['form']=json_decode($this->db->get_where('forms',array(
'id' => $id
))->result()[0]->form_sections);
This gives me following result on printing :
Array
(
[form] => Array
(
[0] => Personal_Information
[1] => Education_
[2] => Professional_Life
)
)
Now i have details against each of these array indexes that i am trying to assign them as below
foreach ($form['form'] as $value){
$value->details=$this->db->get_where('formdata',array(
'form_section' => $value
))->result();
}
Which gives me following error
Message: Attempt to assign property 'details' of non-object
can someone please help me to sort out the issue , i have to assign the index and loop in it in my view
This should help understand and clear up the message:
// Custom data
$Person_Info = 404; // Could be any non-object
$array = array("form" => array( 0 => $Person_Info) );
foreach( $array['form'] as $value ){
$results = new stdClass();
$results->name = "User A";
$value->details = $results; // $results are you fetch request
}
// Output: Attempt to assign property 'details' of non-object in php<8.0
// Output: Uncaught Error: Attempt to assign property "details" on int php>=8.0
Try to print_r or var_dump your $value and see what you are getting. It's not an object for some of your array item.
Edit: If ever in doubt about the data. Use if (is_obejct($var)) php.net/is_object or similar checks based on what you need.
I am making my own array from another one, using email field as key value. If there is more results with same email I am amking array_push to existing key.
I am getting always data in my array (with email) and here is the example
Input data
Example data
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}
Error
I am getting error Undefined index: test#test.com and if I debug my array, there is key with value of 'test#test.com', so key is defined (!)
so var $curVal key is undefined
Result
So the goal of foreach is to filter all objects in array with same email, here is the example:
$data = [
'test#test.com' => [
0 => {data},
1 => {data},
...
],
'bla#test.com' => [
0 => {data},
1 => {data},
...
],
];
this line $curVal = $data[$products->custom_product_email]; is useless and is the one provoking the error: you just initialized $data as an empty array, logically the index is undefined.
You should test directly if (!isset($data[$products->custom_product_email])) {
Then explanation: there is a fundamental difference between retreiving the value of an array's index which is undefined and the same code in an isset. The latter evaluating the existence of a variable, you can put inside something that doesn't exist (like an undefined array index access). But you can't store it in a variable before the test.
Did you not see the error message?
Parse error: syntax error, unexpected '{' in ..... from this code
$saved_data = [
0 => {'custom_product_email' => 'test#test.com',...},
1 => {'custom_product_email' => 'test#test.com',...},
2 => {'custom_product_email' => 'bla#test.com',...},
3 => {'custom_product_email' => 'bla#test.com',...},
...
];
Change the {} to [] to correctly generate the array.
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Your next issue is in this code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
// ^^^^^
$data is an empty array that you initialised 2 lines above, so it does not contain any keys or data!
Check, if $data[$products->custom_product_email] is already set in $data array
Try This code
$data = [];
foreach ($saved_data as $products) {
$curVal = isset($data[$products->custom_product_email]) ? $data[$products->custom_product_email] : null;
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}
I am having a problem accessing an object in a multidimensional array.
THE CONTEXT
Basically, I have an object (category) which consists of Name, ID, ParentID and more. I also have an array ultimateArray which is multidimentional.
For a given category, I am writing a function (getPath()) that will return an array of ids. For example, an object named Granny Smith has a parentID of 406 and is therefore a child of Food(5) -> Fruits(101) -> Apples(406). The function will return either an array or string of the ids of the objects parents. In the above example this would be: 5 -> 101 -> 406 or ["5"]["101"]["406"] or [5][101][406]. Food is a root category!
THE PROBLEM
What I need to do is use whatever is returned from getPath() to access the category id 406 (Apples) so that I can add the object Granny Smith to the children of Apples.
The function $path = $this->getPath('406'); is adaptable. I am just having difficulty using what is returned in the following line:
$this->ultimate[$path]['Children'][]= $category;
It works when I hard code in:
$this->ultimate["5"]["101"]["406"]['Children'][]= $category;
//or
$this->ultimate[5][101][406]['Children'][]= $category;
Any help is much appreciated.
Suppose you have the array like below
<?php
$a = array(
12 => array(
65 => array(
90 => array(
'Children' => array()
)
)
)
);
$param = array(12, 65, 90); // your function should return values like this
$x =& $a; //we referencing / aliasing variable a to x
foreach($param as $p){
$x =& $x[$p]; //we step by step going into it
}
$x['Children'] = 'asdasdasdasdas';
print_r($a);
?>`
You can try referencing or aliasing it
http://www.php.net/manual/en/language.references.whatdo.php
The idea is to make a variable which is an alias of your array and going deep from the variable since we can't directly assigning multidimensional key from string (AFAIK)
output
Array
(
[12] => Array
(
[65] => Array
(
[90] => Array
(
[Children] => asdasdasdasdas
)
)
)
)
You can use a recursive function to access the members. This returns NULL if the keys do not correspond with the path, but you could also throw errors or exceptions there. Also please note that i have added "Children" to the path. I have done this so you can use this generically. I just did an edit to show you how to do it without children in the path.
<?php
$array = array(1 => array(2 => array(3 => array("Children" => array("this", "are", "my", "children")))));
$path = array(1, 2, 3, "Children");
$pathWithoutChildren = array(1, 2, 3);
function getMultiArrayValueByPath($array, $path) {
$key = array_shift($path);
if (array_key_exists($key, $array) == false) {
// requested key does not exist, in this example, just return null
return null;
}
if (count($path) > 0) {
return getMultiArrayValueByPath($array[$key], $path);
}
else {
return $array[$key];
}
}
var_dump(getMultiArrayValueByPath($array, $path));
$results = getMultiArrayValueByPath($array, $pathWithoutChildren);
var_dump($results['Children']);
Starting from a variable called $data, which is an associative array which includes an object, and whose printed value is this:
Array
(
[item] => stdClass Object
(
[id] => 1
[tipo] => 0
[idioma] => es
[nombre] => Artículo de prueba
[titulo] => Esto es un artículo de prueba
[alias] => articulo-de-prueba
[texto] => Lorem ipsum etc etc
[url] =>
[video] =>
[fecha_c] => 2012-11-27 10:50:37
[fecha_m] => 2012-11-27 17:00:00
[fecha_p] => 2012-11-28 00:00:00
[destacado] => 0
[status] => 1
)
[imagenes] => Array
(
)
)
I need to filter its value and assign it to another array, this way:
protected function load_form($data = '') {
$this->load->helper('form');
// If item data have been sent, pass it to the form view to edit it.
// Else display empty form for new item.
if (! empty($data)) {
// Data can be an associative array with an object and another array or just an object
if (array_key_exists('item', $data)) {
$this->_vars['item'] =& $data['item'];
}
else {
$this->_vars['item'] =& $data;
}
if (array_key_exists('imagenes', $data)) {
$this->_vars['imagenes'] = $data['imagenes'];
}
}
$view = $this->load->view(ADMIN_FORMS_PATH . $this->_controller . '_form', $this->_vars, true);
/*DEBUG*/ echo $view; // just for debugging purposes
}
The first assignment generates these errors:
A PHP Error was encountered Severity: Notice Message: Undefined index:
item Filename: core/Admin_Controller.php Line Number: 205
A PHP Error was encountered Severity: Notice Message: Object of class
stdClass could not be converted to int Filename:
core/Admin_Controller.php Line Number: 205
It behaves like the item index doesn't exist, and it does. Also, it tries to convert the object to an integer.
Why does it happen and what should I do to fix it?
EDIT:
I was doing &= instead of =&. That's the reason of the errors.
Anyway, the problem persists and the code seems to stop.
EDIT2:
Trying to redefine the problem. It might be something related to CodeIgniter, so I've added the whole function, including CodeIgniter functions.
The load_form() method can be invoked from a request to create a new item, in which case $data is empty, or from a request to edit a given item (in $data). In the first case (creation), the debug line is executed, but not in the second case (edition).
This may be your issue. Near the end you have"$datos['imagenes'];" where it should be "$data['imagenes'];"
if (! empty($data)) {
// Data can be an object, or an array with object + array of images
if (array_key_exists('item', $data)) {
$this->_vars['item'] &= $data['item'];
}
else {
$this->_vars['item'] = $data;
}
if (array_key_exists('imagenes', $data)) {
$this->_vars['imagenes'] = $data['imagenes'];
}
}
Problem solved. It was too simple.
It was inside the view. I was trying to echo:
$item['id']
instead of
$item->id
The item data is being retrieved as an object, not an array. It was causing the problem silently, without any warning, notice or error.
Anyway I appreciate your quick help.
I have an array like this:
Array ( [PlasticContainmentTrained] => 0 [AvoidDustSpreadTrained] => 1 [PostRenCleaningTrained] => 0 [EntranceWarningSign] => 1 [IntObjectCovered] => 1 [IntHVAC] => 0 [IntWindowClosed] => 1 [ExtWindowClosed] => 0 [IntDoorClosed] => 1 [ExtDoorClosed] => 0 [DoorCovered] => 1 [IntFloorCovered] => 0 [ExtGroundCovered] => 1 [ExtVertContainment] => 0 [WasteContained] => 1 [AllChipsDebris] => 0 [WorkAreaSurface] => 0 [DustClearanceTesting] => 1 [WasteHandlingTrained] => 1 [MaintainContainmentTrained] => 0 [PostingWarningSignTrained] => 1 [DescriptionOfRenovation] => bnfdbndljnbljdfnbljkdnfljn [TrainedWorkers] => jvndfjnvdfvjndfljvndfljvn [DustSamplingTechnicanNames] => jvnfjdfnlvjdfjvndfljndflj [QualificationCopies] => dfjvdjf [KitUsed] => vjnjkdsfnvljdnvdjfvndfjbnjgbnndfn [TestLocations] => jdfjnvljndfvjdnfvjdnfvjkfnlj [CertifiedRenPerformed] => fdjndfljvndfljvndfjvndflk [ReportAttachPath] => undefined [IAccept] => undefined [ProjectId] => 1 )
and i want to filter this array but only 'undefined' values not '0'. i have used array_filter() function for this:
function filterValue($var)
{
if($var=='0')
{
return 0;
}
elseif($var!='undefined')
{
return $var;
}
}
$this->data = array_filter($_POST, "filterValue");
but it also filters '0' values. how can i do this.
Please any body help me...
That's because '0' evaluates to boolean false. Just check for undefined, and return false if it is undefined, true if it isn't:
<?php
$data = array_filter( $data, function( $element ) {
return $element !== 'undefined';
});
You could also create a callback function to reuse like your original example, which helps cut down on repeated code. This custom callback function also trims spaces, and allows you to specify an array of values you don't want filtered out:
// Customized "array_filter" callback to preserve "0" in submitted values:
function empty_array_filter($val) {
$val = trim($val);
$allowed_vals = array('0'); // List of values to keep (e.g. these should not be treated as "false").
return in_array($val, $allowed_vals, true) ? true : ( $val ? true : false );
}
Then use your array filter with your custom callback like so:
// Use the custom callback instead of the default one:
$array_data = array_filter($array_data, 'empty_array_filter');