fetch value from a given array - php

I have an array stored in $result like this
$result=$array
by using echo $result i get the following array
Array
(
[success] => 1
[product] => Array
(
[id] => 83
[seo_h1] =>
[name] => Beer Week
[manufacturer] => The Boxer Store
[model] => WPEB/0413/74/BW
[sku] => WPEB/0413/74/BW
[reward] => 0
[points] => 0
[image] => asd
[images] => Array
(
[0] => asd
)
[quantity] => 4
[price] => Rs.599
[special] =>
[discounts] => Array
(
)
[options] => Array
(
[0] => Array
(
[product_option_id] => 42
[option_id] => 25
[name] => Size Option
[type] => select
[option_value] => Array
(
[0] => Array
(
[product_option_value_id] => 165
[option_value_id] => 72
[name] => Large
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
[1] => Array
(
[product_option_value_id] => 166
[option_value_id] => 73
[name] => XL
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
[2] => Array
(
[product_option_value_id] => 163
[option_value_id] => 70
[name] => Small
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
[3] => Array
(
[product_option_value_id] => 164
[option_value_id] => 71
[name] => Medium
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
)
[required] => 1
)
)
[minimum] => 1
[rating] => 0
[description] => as
[attribute_groups] => Array
(
)
[date_added] => 2014-09-30 12:35:12
[date_modified] => 2014-10-17 17:33:46
[currency] => INR
[status] => 1
)
)
i am able to fetch the result individually like this
$finalid = $array['product']['id'];
echo $finalid;
but wish to fetch each and every data even the inner most values using for loop. for this i tried this
$c=count($result);
for ( $i=0; $i < $c; $i++)
{
echo $array[$i]['id'];
echo $array[$i]['images'][0];
echo $array[$i]['options'][0]['product_option_id'];
echo $array[$i]['images'][0]['option_value'][0]['product_option_value_id'];
echo $array[$i]['images'][0]['option_value'][1]['product_option_value_id'];
}
but it didn't displayed any result can anyone tell how it can be done

Use:
$products = $result['product'];
foreach ( $products as $product )
{
echo $product['id'];
echo $product['images'][0];
echo $product['options'][0]['product_option_id'];
echo $product['images'][0]['option_value'][0]['product_option_value_id'];
echo $product['images'][0]['option_value'][1]['product_option_value_id'];
}

You may want a recursive function like this to print your multidimensional arrays:
function printIt($data){
if (is_array($data)){
foreach ($data as $index=>$slice){
if (is_array($slice)){
printIt($slice);
}else{
echo $index.": ".$slice."<br>";
}
}
}else{
echo $data."<br>";
}
}
printIt($yourArray);

Use foreach instead,
foreach ( $array['product'] as $product)
{
echo $product['id'];
echo $product['images'][0];
echo $product['options'][0]['product_option_id'];
echo $product['options'][0]['option_value'][0]['product_option_value_id'];
echo $product['options'][0]['option_value'][1]['product_option_value_id'];
}
Here you will be looping inside each element of $array['product'] and for each loop $product will have the current element of $array['product'].
The mistake in your attempt was in [$i]. For each loop $i would have 0,1,2 etc and the array index would be $array['product'][0],etc but there is no element of that sort. Your method works if your array is an Indexed array, but here it is an Associative Array.

Try this,
<?php
foreach($result as $res){
echo '<pre>'; echo $res['id'];
if(is_array($res['options']) && !empty($res['options'])) {
foreach($res['options'] as $option) {
echo '<pre>'; echo ($option['product_option_id']);
if(is_array($option['option_value']) && !empty($option['option_value'])) {
foreach($option['option_value'] as $option_value) {
echo '<pre>'; echo $option_value['product_option_value_id'];
}
}
}
}
?>

Related

PHP: Comparison of array value not working?

I am trying to comparing array value, if value found if(isset($row['height']) == ['3455']) then print the array value but it is not working it is return all the array which includes not matching value too.
How will I compare a value and if value found then print that single value of array not all value.
Here is my print_r value
Array
(
[0] => Array
(
[id] => 1
[name] => Bradeley Hall Pool
[postcode] => CW1 5QN
[lat] => 53.10213
[lon] => -2.41069
[size] => 1.60
[pegs] => 21
[distance] => 26.6
[suitability] => Array
(
[0] => Array
(
[species] => Barbel
[species] => 1
[record] => 1
[weight] => 2.721554
[length] => 40
[height] => ['abc','345m','3455']
)
)
)
[1] => Array
(
[id] => 2
[name] => Farm Pool
[postcode] => CW9 6JQ
[lat] => 53.320502
[lon] => -2.549049
[size] => 0.88
[pegs] => 8
[distance] => 15.4
[suitability] => Array
(
[0] => Array
(
[species] => Barbel
[species] => 1
[record] => 1
[weight] => 2.721554
[length] => 40
[height] => ['33','3455','3mnc']
)
)
)
)
My code -
foreach( $cursor as $row){
foreach ($row['suitability'] as $item) {
if(isset($item['height']) == ['3455']){
echo 'yes';
echo '<pre>';
print_r($item['height']);
} else{
echo 'no';
}
}
}
I think the most obvious issue may be that [height] => ['abc','345m','3455'] is not an array, otherwise the print_r() would have shown it as one. So it must be a string.
So this would work
foreach( $cursor as $row){
foreach ($row['suitability'] as $suit) {
// can we find the string in there somewhere
if (strpos($suit['height'], '3455') !== false) {
echo 'yes ';
echo $suit['height'];
echo PHP_EOL;
} else{
echo 'no';
}
}
}
There are shorter ways, but you should use isset to check for the existence of the array key. Once you know it is present, you can in_array to check for a specific value within the height array.
<?php
foreach($cursor as $row){
// Check if the row has the key `suitability`.
if (isset($row['suitability'])) {
foreach ($row['suitability'] as $item) {
// Check if the item has the key `height`.
if (isset($item['height'])) {
// Assuming `height` is always an array.
if (in_array('3455', $item['height']) {
// Yes.
}
}
}
}
}

How to Sum Array Associative with 2 key values

I'm try to Sum values with 2 keys condition in associative array, but didn't get any result and only not like expected.
my array:
Array
(
[0] => Array
(
[pid] => P1
[rid] => 1
[price] => 100
)
[1] => Array
(
[pid] => P1
[rid] => 1
[price] => 120
)
[2] => Array
(
[pid] => P1
[rid] => 1
[price] => 130
)
[3] => Array
(
[pid] => P2
[rid] => 1
[price] => 80
)
[4] => Array
(
[pid] => P2
[rid] => 1
[price] => 120
)
[5] => Array
(
[pid] => P2
[rid] => 2
[price] => 150
)
);
i have tried some code from
How to GROUP BY and SUM PHP Array? or Grouping arrays in PHP
and then the code becomes:
$groups = array();
foreach ($array as $item) {
$key = $item['pid'];
if (!array_key_exists($key,$groups)) {
$groups[$key] = array(
'pid' => $item['pid'],
'rid'=>$item['rid'],
'price' => $item['price']
);
} else {
$groups[$key]['price'] += $item['price'];
}
}
i exptected output array:
Array
(
[0] => Array
(
[pid] => P1
[rid] => 1
[price] => 350
)
[1] => Array
(
[pid] => P2
[rid] => 1
[price] => 200
)
[2] => Array
(
[pid] => P2
[rid] => 2
[price] => 150
)
);
I have no idea how to write with array_reduce as well as foreach to resolve this, please hit me by other refrence or help me to solve this.
If $data is your input array, you can use below code
$r = array();
foreach ( $data as $d ) {
$key = $d['pid'] . '-' . $d['rid'];
if( !isset ( $r[$key] ) ) {
$r[$key] = $d;
} else {
$r[$key]['price'] += $d['price'];
}
}
echo '<pre>';
print_r($r);
die;

PHP traversing a multidimensional array

I have the following multidimensional array:
Array
(
[0] => 57950340
[1] => SALE-86
[2] => COMPLETE
[3] =>
[4] => 333
[5] => 819
[6] => Array
(
[0] => Array
(
[number] => 1
[product] => Array
(
[id] => 90316
[name] => CLASSIC COCKTAIL
)
[quantity] => 1
[price_variation] => 1
[modifiers] => Array( )
[notes] =>
[unit_price] => 16.3636
[unit_tax] => 1.63636
)
[1] => Array
(
[number] => 2
[product] => Array
(
[id] => 90316
[name] => CLASSIC COCKTAIL
)
[quantity] => 1
[price_variation] => 1
[modifiers] => Array ( )
[notes] =>
[unit_price] => 16.3636
[unit_tax] => 1.63636
)
)
)
I'm trying to loop through the array so that I can echo the name of the product items (held within the array at key 6 and echo each of these out on a separate line with the unit price and an the initial order ID (key 0 of the initial array).
I've been trying to do this for a few hours but am going round in very confusing circles, can anyone shed any light on how I can do this?
<?PHP
$multi_dimensional_array = [...]; // Your array here
$order_id = $multi_dimensional_array[0];
$products_array = $multi_dimensional_array[6];
foreach($products_array as $product) {
echo $product['product']['name']." costs ".$product['unit_price'];
echo " - ORDER: ".$order_id;
echo "<br/>";
}
?>
Useforeach and is_array() to check if the values is array then foreach to access the inside variables then lastly you can echo it.
foreach($array as $key => $val)
{
if(is_array($val){
foreach($val as $key2 => $val2)
{
//print_r($val2); to see the actual data you are accessing
echo "ID: " . $val2['product']['id']. ' Product Name: ' . $val2['product']['name'] . ' Quantity: ' . $val2['quantity'];
}
}
}

Combine php array duplicate values

I have a php array that just like this:
Array
(
[0] => Array
(
[product] => 2
[price] => 30
[qnty] => 1
)
[1] => Array
(
[product] => 2
[price] => 30
[qnty] => 1
)
[2] => Array
(
[product] => 1
[price] => 250
[qnty] => 1
)
)
and I want to combine the duplicate values, add "qnty" index value and print that array like this:
Array
(
[0] => Array
(
[product] => 2
[price] => 30
[qnty] =>2
)
[1] => Array
(
[product] => 1
[price] => 250
[qnty] => 1
)
)
How can i combine this array. Please help me
try the code below. I am assuming the your array name is $products
$merged = array();
foreach($products as $product) {
$key = $product['product'];
if(!array_key_exists($key, $merged)) {
$merged[$key] = $product;
}
else {
$merged[$key]['qnty'] += $product['qnty'];
}
}
echo '<pre>';
print_r($merged);
exit;

cannot find value in array

I can't see where I am wrong with this code so I kindly ask for your help.
I have two arrays:
Array (
[0] => Array (
[description] => Generali di Proprieta'
[idmov] => 34
[mov] => Manutenzioni
[total] => 8000
)
[1] => Array (
[description] => Generali di Proprieta'
[idmov] => 35
[mov] => Assicurazioni
[total] => 6000
)
[2] => Array (
[description] => Generali di Proprieta'
[idmov] => 36
[mov] => Cancelleria Postali
[total] => 1850
)
[3] => Array (
[description] => Generali di Proprieta'
[idmov] => 37
[mov] => Bancarie passive
[total] => 700
)
[4] => Array (
[description] => Generali di Proprieta'
[idmov] => 38
[mov] => Amministrazione
[total] => 15000
)
)
and
Array (
[0] => Array (
[center] => 8
[caus] => 34
[total] => 38175.04
)
[1] => Array (
[center] => 8
[caus] => 35
[total] => 6132.00
)
[2] => Array (
[center] => 8
[caus] => 36
[total] => 223.80
)
[3] => Array (
[center] => 8
[caus] => 37
[total] => 114.70
)
[4] => Array (
[center] => 8
[caus] => 38
[total] => 14625.07
)
[5] => Array (
[center] => 8
[caus] => 39
[total] => 7450.48
)
I use this function
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['caus'] === $id) {
return $key;
}
}
return null;
}
to look in array B for each item of array A with this code:
for($i=0;$i<$length;$i++){
if(searchForId($voce_bdg[$i]['idmov'], $voce_actual)){
$key=searchForId($voce_bdg[$i]['idmov'], $voce_actual);
$actual=$voce_actual[$key]['importo'];
echo '<td class="report">'.number_format($actual,2,',','.').'</td>';
}else{
echo '<td class="report">0,00</td>';
}
}
It works for every item like a charm except for the first item where it returns 0.
Where am I wrong??
Thanks in advance for your help!
Lelio
PHP treats the index 0 as a false. As such, if you find your result in index zero, it won't pass the if() statement you have.
Since your function returns null if no record found, why not try to check for null?
for($i = 0; $i < $length; $i++)
{
// Use is_null() check below. If it is not null, it is found.
// Also, instead of doing searchForId() twice, just do it once and check for the result.
$key = searchForId($voce_bdg[$i]['idmov'], $voce_actual);
if(! is_null ($key))
{
$actual = $voce_actual[$key]['importo'];
echo '<td class="report">'.number_format($actual,2,',','.').'</td>';
}
else
{
echo '<td class="report">0,00</td>';
}
}
try replacing operator === for ==
It does return something. It return 0 since the key is 0. But your if() interpret it as a "false"
change
if(searchForId($voce_bdg[$i]['idmov'], $voce_actual)){
with
if(searchForId($voce_bdg[$i]['idmov'], $voce_actual) != null){

Categories