I can't get stdClass Object value in Codeigniter - php

I cant get object value in codeigniter.
The code message like that : Message: Trying to get property 'img' of non-object
foreach ($getAllProductsQuality as $productsQuality) {
$getMainImage = $t->products_model->getImage(array('sku', 'img', 'file', 'folder', 'title'), array('status' => 1, 'main' => 1, 'sku' => $productsQuality->sku));
$getDataImages = $t->products_model->getImage(array('sku', 'position','img'), array('status' => 1,'position' => 2, 'sku' => $productsQuality->sku));
print_r($getDataImages->img);//problem is here
$productsImg = base_url() . 'assets/img/preparing-image.jpg';
$productsImgTitle = 'Preparing Image';
if (!empty($getMainImage->img)) {
$productsImg = image(adminURL . $getMainImage->img, 268, 357);
$productsImgTitle = $getMainImage->title;
}
and i try print_r for value:
print_r($getDataImages->img);
my query output like that:
stdClass Object
(
[sku] => 37205
[position] => 2
[img] => uploads/product/Almeras/almeras-23634-110-top.png
)
stdClass Object
(
[sku] => 37326
[position] => 2
[img] => uploads/product/Almeras/almeras-23642-956-top.png
)
what i do wrong ?

It seems your query
$t->products_model->getImage(array('sku', 'position','img'), array('status' => 1,'position' => 2, 'sku' => $productsQuality->sku));
is returning nothing, so there probably is no image. You can test this by using var_dump($getDataImages).
Regarding your edit:
I think the first two items in $getAllProductsQuality do have an image associated (37205 and 37326) but there is probably another $getAllProductsQuality without an image associated. How many items are in this $getAllProductsQuality array? Can you put var_dump($getDataImages) in front of the print_r?

Related

How do i get separate field in array

I want to get separate field in array, I have array and some fields but I need single fields how can get below I given my code and out put of data(print_r) please how can I do this one, I'm new in php.
I want only for 'code' field only how can I get...
print_r() I'm getting this output:
Array ( [0] => Array ( [id] => 1 [code] => kg1 [name] => Kindergarden [status] => 1 [craeteddate] => 2022-02-03 17:33:05 )
My php code:
$data['classes'] = $this->enquiryform_model->get_class();
$class_code = $data['classes']['code'];
you have two arrays. 1 inside another. So to get the code you need to do this.
<?php
$data['classes'] = array( 0 => array( 'id' => 1, 'code' => 'kg1', 'name' => 'Kindergarden', 'status' => 1, 'craeteddate' => '2022-02-03 17:33:05' ));
$class_code = $data['classes'][0]['code'];
echo $class_code;
echo "\n";
$class_code = $data['classes'][0];
echo $class_code['code'];
?>
Here is the working example

Printing parts of an array in PHP

please excuse if this question is already answered elsewhere, but I just don't know what to search for, since I usually don't work with php.
I've got the following array:
(
[0] => Array
(
[login] => name23
[id] => 12356
)
[1] => Array
(
[login] => name12
[id] => 12345
)
[2] => Array
(
[login] => name34
[id] => 12367
)
)
And I'd like to only print the login-names, so in this example name23, name12, name34 (But I never know how many there are).
I've tried several approaches with foreach, which didn't work.
What is working, but only for one username is this:
echo $contributors[0]['login'];
How can I display all login-names?
Any help would be much appreciated.
Thanks in advance!
array_map is a universal function for tasks like this, in your case, this code would work:
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
print_r(array_map(function($data) { return $data['login']; }, $array));
Manual: https://www.php.net/array-map
But for your specific task, array_column is simpler, as recommended by Aghilan B.
There is also array_walk function that can be used like this:
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
array_walk($array, function($data) { print $data['login'] . "\n"; });
That can be useful if you want to do more with the logins than just printing it, it would not need to iterate twice.
You can use array_column() Function
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
$login_array = array_column($array, 'login');
print_r($login_array);
Output
Array
(
[0] => "name23"
[1] => "name12"
[2] => "name34"
)
Use implode(', ', $login_array); to print as a string with commas

Array index stuck at [0]

I am trying to create an array out of looped data. The variables contain looped data. All works fine, but when array is outputted, the index gets stuck at 0 and doesn't move up from 0 to 1 etc. I wonder what the problem is and how I can get this fixed.
Thanks.
$productinfo = array(
array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" )
);
$productinfojson= json_encode($productinfo);
$output = json_decode($productinfojson, TRUE);
echo "<pre>";
print_r( $output );
echo "</pre>";
The above outputs:
Array
(
[0] => Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
)
Array
(
[0] => Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
)
UPDATE if only one array is used.
code:
$productinfo = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" );
OUTPUT
Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
The issue stems straight from your array creation. There doesn't seem to be a loop anywhere in your code either....
Anyways, lets sort out your array creation. I assume you're getting the data from a database/data source and assigning it to variables, inputting it into an array? Well the way you currently have it, it's overwriting the first index element in the array.
Disclaimer: The below is pseudo code, until you update with your actual loop code..
$productinfo = array();
while($row = FETCH_DATA_FROM_SQL()) {
// assign it to variables here...?
$productinfo[] = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link"
);
}
That will add each element to the new $productinfo array and you should be able to loop through the elements correctly.
One more thing to note, you're decoding your json like this:
$output = json_decode($productinfojson, TRUE);
That second parameter (TRUE), turns it into an associative array, not an object. So when you loop it as an object like below:
foreach($response->products->product as $product) {...
It isn't going to work. If you want it as an object, remove the second parameter (TRUE), otherwise loop it as an array:
foreach($response['products']['product'] as $product) {...

PHP loop through array of object gives unexpected result

I have the following PHP code to set parentId for each post.
The parentId of each data all become the last post ID.
What's wrong with my logic?
btw, if I change it to array, everythings becomes ok. Please help!
$data = array(
(object)array('name' => 'myname')
);
$posts = array(
(object)array('ID' => 1, 'data'=>$data),
(object)array('ID' => 2, 'data'=>$data),
(object)array('ID' => 3, 'data'=>$data)
);
foreach($posts as &$post){
$post->data[0]->parentId = $post->ID;
}
print '<pre>';print_r($posts);die;
die;
Results:
Array
(
[0] => stdClass Object
(
[ID] => 1
[data] => Array
(
[0] => stdClass Object
(
[name] => myname
[parentId] => 3 // expect to be 1
)
)
)
[1] => stdClass Object
(
[ID] => 2
[data] => Array
(
[0] => stdClass Object
(
[name] => myname
[parentId] => 3 // expect to be 2 !!!
)
)
)
[2] => stdClass Object
(
[ID] => 3
[data] => Array
(
[0] => stdClass Object
(
[name] => myname
[parentId] => 3
)
)
)
)
All things considered, the real issue here is, after a second glance at your code, the way you're setting the data property. Since PHP5, objects are passed/assigned by reference by default. Remember the PHP4 days? ($newInstance = &new SomeClass();), PHP5 uses references for objects now, so when you do:
$data = array(
(object)array('name' => 'myname')//create object
);
Then, all three objects are assigned the same object (By reference!), so if you change it for the first time around, all three instances will reflect the same change!
I've recently posted a lengthy answer on references in loops here, it might be worth a look, because looping by reference isn't the best way to go about your business.
Some code-review:
Instead of constructing all these arrays, and cast them to objects individually, I'd just do this:
$data = array(
array('name' => 'myname')
);
$posts = array(
array('ID' => 1, 'data'=>$data),
array('ID' => 2, 'data'=>$data),
array('ID' => 3, 'data'=>$data)
);
foreach($posts as $k => $post)
{
$posts[$k]['data'][0]['parentId'] = $posts[$k]['ID'];
}
$posts = json_decode(json_encode($posts));//turns everything into objects
print_r($posts);
At first, it might seem inefficient to json_encode something, just to json_decode it, but json_decode returns objects, instead of associative arrays by default. I've ran a few tests scripts not too long ago, as it turned out: the encode-decode approach was actually faster than casting each associative array...
Okay, i misunderstood your problem, due to the fact that you reuse the data object you end up with a reference problem, this can be avoided by using clone, as seen below
<?php
$data = (object) array('name' => 'myname');
$posts = array(
(object) array('ID' => 1, 'data'=> array(clone $data)),
(object) array('ID' => 2, 'data'=> array(clone $data)),
(object) array('ID' => 3, 'data'=> array(clone $data))
);
foreach($posts as $postKey => $post){
$posts[$postKey]->data[0]->parentId = $posts[$postKey]->ID;
}
print '<pre>';
print_r($posts);

Creating arrays dynamically using PHP

Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:
$placea = "place a";
$placeb = "place b";
$myarray = array();
echo "<pre>";
print_r($myarray);
echo "</pre>";
what i want to be able to do:
Array
(
[0] => [Place A] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 001
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 002
[RoomAvail] => true
[Date] => 12.04.2011
)
) Array
(
[1] => [Place B] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 101
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 102
[RoomAvail] => true
[Date] => 12.04.2011
)
)
)
how would i write that out in php? sorry if its bleek and/or the array structure is incorrect
So you just need to use the array initializer repetitively.
If you want to initialize an array in PHP with some values, say 1 through 4, you make a call like:
$foo = array(1, 2, 3, 4);
And if you want to make an associative array, where you store some key/value pairs, you make a call like:
$foo = array('key' => 'value', 'other key' => 'other value');
But you can of course nest calls, and mix and match layers of associative and non associative arrays to achieve something like your example, e.g.:
$foo = array(
'Place A' => array(
// note use of first array on the next line is
// to generate structure like [0] => 'Accomodation' => ...
array('Accomodation' => array(
'RoomId' => '001',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '002',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
),
'Place B' => array(
array('Accomodation' => array(
'RoomId' => '101',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '102',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
)
);
This will very nearly produce what you're looking for, to make it replicate exactly what you have you would wrap each 'Place A' with an array and each "place" would get its own assignment to some variable $foo (I assumed this wasn't actually what you wanted and wrote something maybe slightly more intuitive).
If you want to have a 'less complicated' array, you have a two arrays, one fore place a and one for place b and then merge them using array_merger() http://www.php.net/manual/en/function.array-merge.php.
Study up on the array functions control structures in the manual. Many different ways of achieving bloated arrays uglying up your code.
This would dynamically create an array.
foreach($soapResponse as $key1 => $value1){
foreach($value as $key2 => $value2){
// $key1 = Place A or B
// value1 = array of values
$arrayResponse[$key1][$key2] = $value2;
}
}

Categories