How do i get separate field in array - php

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

Related

I can't get stdClass Object value in Codeigniter

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?

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

How to group database table data by two columns and output as json?

I am trying to get JSON(PHP) from PhpMyAdmin(Mysql). It actually need to look like:
[{ “converterno”: ”1”, “zoneno”: {“1a”, “codeid”:[“t1”,”t2”,”t3”]}, “zoneno”: {“1b”, “codeid”:[“t21”,”t0”,”t13”]}},{ “converterno”: ”2”, “zoneno”: {“2a”, “codeid”:[“t023”,”t9”,”t31”]}},………………………..
But what I am actually getting is
[{"converternumber":"1","zonenumber":{"0":"","codeid":["er"]}},{"converternumber":"1","zonenumber":{"0":"wr","codeid":["fxv"]}},{"converternumber":"2","zonenumber":{"0":"b2","codeid":["gffff"]}}]
And I don't know why I am getting Zero's at the starting
The PHP code is:
<?php
$db_name="app1";
$mysql_user="root";
$server_name="localhost";
$connectionn=mysqli_connect($server_name,$mysql_user,"",$db_name);
$n_converternumber= ["converternumber"];
$n_zonenumber= ["zonenumber"];
$n_codeid= ["codeid"];
$sql_query = "select * from addcode";
$result= mysqli_query($connectionn,$sql_query);
while ($row = mysqli_fetch_array($result)){
if(!isset($info[$row['converternumber']])){
$info[$row['converternumber']] = array(
'converternumber'=> $row['converternumber'],
'zonenumber' => array($row['zonenumber'],
'codeid' => array($row['codeid']))
);
}}
echo json_encode($info);
?>
Can anyone kindly tell me where I am going wrong in the "While" loop.
Went through all the code relating to JSON in StackOverFlow, but didn't find anything closer or similar. Tried almost everything and posting this now!!
Hope I would get any help here!
The table in the database is:
Table addcode
After extended discusson, you seem to desire a "grandparent-parent-child" structure. This is super easy to form and a completely associative structure will keep your data very compact and simple to iterate.
*and you should use mysqli_fetch_assoc() instead of the bloating mysqli_fetch_array() because you don't intend to use the indexed elements that it generates.
Code (Demo based on your database screenshot)
while ($row = mysqli_fetch_assoc($result)){
$info[$row['converternumber']][$row['zonenumber']][] = $row['codeid'];
}
The 3-level array would look like this:
array (
1 =>
array (
'1a' =>
array (
0 => 'test007',
1 => 'test006',
2 => 'test0094',
3 => 'test0098',
4 => 'test010',
5 => 'test111',
6 => 'test 008',
7 => 'test112',
8 => 'test004',
9 => 'test002',
10 => 'test001',
),
23 =>
array (
0 => 'rg',
),
'2a' =>
array (
0 => 'test001',
1 => 'test003',
),
'feh' =>
array (
0 => 'ndo',
),
'wr' =>
array (
0 => 'fxv',
),
),
2 =>
array (
'1a' =>
array (
0 => 'test',
),
'b2' =>
array (
0 => 'gffff',
),
),
)

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) {...

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