I want to retrieve a single value from this php array.
My array in PHP is:
Array
(
[0] => stdClass Object
(
[id] => 27
[id_customer] => 19
[my_cart] => Array
(
[c81e728d9d4c2f636f067f89cc14862c] => Array
(
[id] => 2
[qty] => 1
[price] => 39000
[name] => HEBERGEMENT WEB MUTUALISE PREMIUM
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[subtotal] => 39000
)
[a87ff679a2f3e71d9181a67b7542122c] => Array
(
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
)
1
[created_at] => 2020-03-30
)
)
The problem is that I can not get qty, name, price
I tried by doing this in my foreach
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
foreach($data as $s){
echo 'My cart: '.$s;
}
}
}
But nothing is happened! I want to get price, name and qty.
In this line:
echo 'My cart: '.$s;
The variable $s holds an array, not a string. If you follow your data structure, the contents of $s would be similar to this:
Array (
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
So, in order to get name, qty, price, you'd need to change your inner loop to something like this:
foreach ($data as $s) {
echo 'Product name: ' . $s['name'] . '<br>';
echo 'Quantity: ' . $s['qty'] . '<br>';
echo 'Price: ' . $s['price'] . '<br>';
}
What happens when you try to use an array as a string is that it shows up as the string "Array" and will trigger a PHP Notice: Array to string conversion in [location]. I'm guessing this error might be the reason you get nothing, instead of My cart: Array.
To get several keys from my_cart array, try to write the loop like this :
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
$filtered = [];
$keys = ['qty', 'name', 'price']; // the keys
$column_keys = array_flip($keys); // getting keys as values
foreach ($data as $key => $val) {
// getting only those key value pairs, which matches $column_keys
$item = array_intersect_key($val, $column_keys);
if (!empty($item))
$filtered[$key] = $item;
}
echo 'My cart: <br/>';
print_r($filtered);
}
}
I found the solution. When inserting into database I encode it like this htmlspecialchars(json_encode($data)) and decode in with json_decode while getting the $data. So now I have this:
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = json_decode($cd->my_cart);
foreach($data as $row){
echo $row->name;
echo $row->qty;
echo $row->price;
}
}
Related
This question already has answers here:
Looping a multidimensional array in php
(3 answers)
Closed last year.
Here is an array from which I need to sort out the dept name, the full name and the salary , whose salary are above 10000rs.
The array is:
Array
(
[PHP] => Array
(
[0] => Array
(
[name] => Jay
[salary] => 8000
)
[1] => Array
(
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[name] => Mihir
[salary] => 12000
)
)
[Flex] => Array
(
[0] => Array
(
[name] => Vijay
[salary] => 14000
)
)
[System] => Array
(
[0] => Array
(
[name] => Kishan
[salary] => 5000
)
)
)
I am totally confused inside the loops of foreach and don't know how to call each value from the array.
My code allows me to display only names.
Can i know what is the best way to print and work with multidimensional arrays in PHP.
My code:
foreach($newArray as $x=>$x_value){
foreach ($x_value as $y=> $y_value){
if($y_value['salary']>10000)
echo $y_value['name']." has ". $y_value['salary']. ", ";
}
}
Use the following, Tested and working
$filterArray = array();
$i = 0;
foreach($salary as $dept => $employee){
foreach($employee as $index => $data){
if($data['salary'] > 10000){
$filterArray[$i]['deprtment'] = $dept;
$filterArray[$i]['name'] = $data['name'];
$filterArray[$i]['salary'] = $data['salary'];
}
$i++;
}
}
Result :-
Array
(
[1] => Array
(
[deprtment] => PHP
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[deprtment] => PHP
[name] => Mihir
[salary] => 12000
)
[3] => Array
(
[deprtment] => Flex
[name] => Vijay
[salary] => 14000
)
)
Your input is nested array. So you have to use foreach +for loop:
$final_array = array();
foreach($newArray as $x=>$x_value)
{
foreach ($i=0;$i<count($x_value);$i++)
{
if($x_value[$i]['salary']>10000)
{
if(isset($final_array[$x]))
{
array_push($final_array[$x],array("name"=>$x_value[$i]['name'],"salary"=>$x_value[$i]['salary']));
}
else
{
$final_array[$x] = array();
array_push($final_array[$x],array("name"=>$x_value[$i]['name'],"salary"=>$x_value[$i]['salary']));
}
}
}
}
$final_array print dep wise name & salary which is max than 10000
Output :
Array
(
[PHP] => Array
(
[0]=> Array
(
[name] => Raj
[salary] => 15000
)
[1]=> Array
(
[name] => Mihir
[salary] => 12000
)
)
[Flex] => Array
(
[0]=> Array
(
[name] => Vijay
[salary] => 14000)
)
)
)
Here is a simpler solution for looping over the arrays.
foreach ($bigArray as $department => $employees) {
foreach ($employees as $employee) {
if ($employee["salary"] > 10000) {
echo "Department: " . $department;
echo "Employee: " . $employee;
echo "Salary: " . $salary;
} else {
echo $person . " has no money.";
}
}
}
This will output what you were trying to print in your example.
Output for the first employee:
Department: <department name>
Employee: Raj
Salary: 15000
In the future, you should include the department names in your example array since your example doesn't have all of the information you are trying to print; we can't print something that doesn't exist.
I don't know, if i've got you correctly, but if you need to filter out all the people from the sub-arrays (PHP, Flex, System, ...) and then sort them either by their name or salary, you could do it in this or a similar way:
$array = [
'PHP' => [
[
'name' => 'Jay',
'salary' => 8000
],
[
'name' => 'Raj',
'salary' => 15000
],
[
'name' => 'Mihir',
'salary' => 12000
]
],
'Flex' => [
[
'name' => 'Vijay',
'salary' => 14000
]
],
'System' => [
[
'name' => 'Kishan',
'salary' => 5000
]
]
];
$array_people = [];
$array_sorted = [];
$sort_by = 'name'; // Array key name
$sort_desc = false;
$min_salary = 10000;
foreach ($array as $type => $people)
{
foreach ($people as $info)
{
if ($info['salary'] >= $min_salary) {
$array_sorted[] = $info[$sort_by];
$array_people[] = $info;
}
}
}
if ($sort_desc) {
// Sort descending
arsort($array_sorted);
} else {
// Sort ascending
asort($array_sorted);
}
$array_final = [];
foreach (array_keys($array_sorted) as $index)
{
$array_final[] = $array_people[$index];
}
print_r($array_final);
Output:
Array
(
[0] => Array
(
[name] => Mihir
[salary] => 12000
)
[1] => Array
(
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[name] => Vijay
[salary] => 14000
)
)
The first thing you need to do, is to process the main array in a way, that allows you to keep just the items you want - this items need to be stored in a different (empty) array (in this case $array_people).
While detecting the items you need, you've to get out all the values you want to sort by - this can be done at the same time. It's just about creating a new array which will contain just the values you will sort by (in this case $array_sorted).
Then comes the easier part. The next thing to do is sorting the array. There exist a bunch of functions, that can help you with this.
The functions i've used (asort and arsort) are keeping the original key of the item, so you can sort the array containing all the people by the keys of the sorted array (see the code up above).
And that's all, now you have an array with filtered and sorted people :) ... hope, this helps you.
Okay after reading so many solutions I personally believe that some of them are totally confusing for a newbie so here is the solution I actually implemented which is totally simple and easy to understand the flow of multi-dimensional array.
foreach($newArray as $x=>$x_value){
foreach ($x_value as $y=> $y_value){
if($y_value['salary']>10000){
echo "<tr>";
echo "<td>"; echo $y_value['name']; echo "</td>";
echo "<td>"; echo $x; echo "</td>";
echo "<td>"; echo $y_value['salary']; echo "</td>";
echo "</tr>";
}
}
}
The output will be like, (if u use table )
I have this Array but i don't know how to get the [discount_amount] based on the [object_ids].
For example i would like to get the 93 value if my [object_ids] contain 81.
Array
(
[0] => Array
(
[id] => rule_5b0d40cd1408a
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 81
)
[discount_type] => amount
[discount_amount] => 93
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
[1] => Array
(
[id] => rule_5b0d4e0f3b0b4
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 110
)
[discount_type] => amount
[discount_amount] => 50
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
)
You could use a foreach and use in_array to check if the array object_ids contains 81.
foreach ($arrays as $array) {
if (in_array(81, $array["object_ids"])) {
echo $array["discount_amount"];
}
}
Demo
Try with this code .
Assuming $dataArray is the array you have printed.
foreach ($dataArray as $key => $value){
if($value['object_ids'][0] == 83){
$discount_amount = $value['discount_amount'];
}
}
echo $discount_amount
The way I mostly do this is as followed:
# Save retrieved data in array if you want to.
$test = array();
foreach($array as $line){
# Count the row where discount_amount is found.
$test[] = $line['9'];
echo "Result: ".$line['9']. "<br \>\n";
# OR another method is
$test[] = $line['discount_amount'];
echo "Result: ".$line['discount_amount']. "<br \>\n";
}
I have a invoice table in which three columns have comma-separated values. Now I want to show a report in details for each invoice.
For example,
Invoice_id=10
product=1,5,55
category=2,44,25
QTY= 55,2,10
So for the above invoice I want to show each product name and category with qty.
If they are in the right order and have a consistent correlation, you can do that.
For example, you can explode by ',' the fields and create the output in a for loop like this:
//you have to retrieve the data from database, the fields are strings
$product= "1,5,55"
$category= "2,44,25"
$QTY= "55,2,10"
//for each invoice:
$products = explode(',',$product);
$categories = explode(',',$category);
$QTYs = explode(',',$QTY);
for ($i = 0; $i < count($products); $i++){
echo "Product: " . $products[$i] . ", Category: " . $categories[$i] . ", Quantity: " . $QTYs[$i] . ".<br>";
}
hope it helps
foreach(explode(' ', 'Invoice_id=10 product=1,5,55 category=2,44,25 QTY=55,2,10') as $key => $value)
{
$temp[] = explode('=', $value);
}
foreach($temp as $key => $value)
{
$final[$value[0]] = explode(',', $value[1]);
}
echo '<pre>';
print_r($final);
output:
Array
(
[Invoice_id] => Array
(
[0] => 10
)
[product] => Array
(
[0] => 1
[1] => 5
[2] => 55
)
[category] => Array
(
[0] => 2
[1] => 44
[2] => 25
)
[QTY] => Array
(
[0] => 55
[1] => 2
[2] => 10
)
)
I am having a multi-dimensional array. When I access it I get undefined index but I just can't see what I am doing wrong. I very much appreciate if someone has a glue as I am devastating for quite some while now. Thanks!
Dump:
Array
(
[922] => Array
(
[products] => Array
(
[169] => http://www.golf-safari.com/golf_regions/cape_town.asp
)
[company] => stdClass Object
(
[id] => 922
[category_id] => 42
[language_id] => 1
[shipping_from_id] => 0
[name] => Golf-Safari.com
[logo] =>
[company_id] => 922
[area_id] => 414
[country_id] =>
[city_id] => 260
[product_id] => 169
[url] => http://www.golf-safari.com/golf_regions/cape_town.asp
[likes] => 0
[dislikes] => 0
[views] => 0
)
)
)
My access code:
<?php foreach($items as $cmp_id => $company):
$item = $company['company']; // throws undefined index company
$item = $company['products']; // throws undefined index product
?>
<div class="title" title="<?= $item->company ?>">
I am not even getting to the div as error is thrown already on $company['company']
Thanks for all the answers! I don't really know whats wrong. Up to now I always assumed that when there is a dump produced then this dump can be accessed, apparently not. I added my preparation code below.
My preparation code:
foreach($rows as $row)
{
if($row->product_id && !in_array($row->product_id, $products)){
array_push($products, $row->product_id);
}
$products_count[$row->product_id][] = '1';
$ids[$row->id] = $row->id; //store every company id, in order to avoid repetitions count variables
$items[$row->id]['products'][$row->product_id] = $row->url; //cities products
$items[$row->id]['company'] = $row;
}
if($products && is_array($products)){
$query = DB::table('products');
$query->select('id', "name_$this->language AS product");
$query->whereIn('id', $products);
$product_names = $query->get();
}
$sub['items'] = array(
'items' => $items,
'product_names'=> $product_names
);
$item = $company['product']; // throws undefined index product
In here you are passing the wrong key use $item = $company['products'];
print_r($company['products']);
In $company['company'] its an object so you can access the values by the following way
echo $company['company']->name;
the array has about 3 layers. i'll go ahead and assume that the $items is the outtermost layer. according to your structure, your code should look like this:
foreach($item[922] as $cmp_id => $company){
$$cmp_id = $company //converts the index of the item[922] into a variable and assign them the values
$item = $$cmp_id['company'];
$item = $$cmp_id['product'];
}
the first $item will hold this value
[company] => stdClass Object
(
[id] => 922
[category_id] => 42
[language_id] => 1
[shipping_from_id] => 0
[name] => Golf-Safari.com
[logo] =>
[company_id] => 922
[area_id] => 414
[country_id] =>
[city_id] => 260
[product_id] => 169
[url] => http://www.golf-safari.com/golf_regions/cape_town.asp
[likes] => 0
[dislikes] => 0
[views] => 0
)
the second one will hold
(
[169] => http://www.golf-safari.com/golf_regions/cape_town.asp
)
they both contain arrays, i don't think you can use them in the div because none of the new $item arrays has an index [company]. to get the innermost arrays, change the codes to
foreach($items[922][company] as $key => $value){ //or $items[922][products]
$$key = $value;
}
you'll get all the values with their indices as the variable name eg
$category_id =42;
In your example you're overwriting $item each time you declare it. Here is a sample of how to loop through the array - http://phpfiddle.org/lite/code/tr0c-u9vh
foreach($items as $comp_id => $company){
$item = $company['products'];
$company_name = $company['company']['name'];
print_r($item); // because this is still an array
echo $company_name; // this is a specific item
}
You could also use PHP's recursive iterator class - http://php.net/manual/en/class.recursiveiteratoriterator.php
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($items));
foreach($iterator as $key=>$value){
echo $key. "\t" . $value . "\n";
}
In essence by calling it like this you can flatten the array. http://phpfiddle.org/lite/code/5p3h-fb21
foreach(['variable_by_which_get_dump']['922'] as $values)
{
foreach($values as $get_subvalue)
{
foreach($get_subvalue as $get_final_subvalue)
{
echo $get_final_subvalue;
echo '<br>';
}
}
}
How can I loop through an array like this and retrieve the id and echo it to the screen? Also how can I do a loop and find the one with the highest id?
Array
(
[articles] => Array
(
[0] => Array
(
[id] => 650
)
[1] => Array
(
[id] => 649
)
[2] => Array
(
[id] => 645
)
[3] => Array
(
[id] => 399
)
);
You can do this with foreach
foreach ($array['articles'] as $value)
{
echo "Id is: ".$value['id'];
}
And you can get with max() function:
foreach($array['articles'] as $article)
{
$ids[] = $article['id'];
}
echo "Max Id is: ".max($ids);
Or you can do get value and max id with one foreach.
foreach($array['articles'] as $article)
{
echo "Id is: ".$article['id'];
$ids[] = $article['id'];
}
echo "Max Id is: ".max($ids);
Say $arr['articles'] contains your array.Then using a foreach you can loop through the array and just echo it.
$arr = array('articles' => array(
'0' => array('id' => 650),
'1' => array('id' => 649),
'2' => array('id' => 645),
'3' => array('id' => 399)
)
);
foreach($arr['articles'] as $val){
echo $val['id'].'</br>';
}
Try
foreach ($arrayvar['articles'] as $value)
{
echo $value['id']."<br>";
}