Traverse an STD Class object inside an array - php

I've send an Array with data through FormData with Ajax.
I json encoded it first before sending it through and decoded it back at the PHP side.
My problem is this: "Trying to get property 'ID' of non-object" Or "Illegal string offset ID"
which is weird, since my array is like:
array(7) {
[0]=>
object(stdClass)#779 (2) {
["ID"]=>
string(1) "1"
["Value"]=>
string(19) "Onbeperkt helpdesk."
}
[1]=>
object(stdClass)#780 (2) {
["ID"]=>
string(1) "2"
["Value"]=>
string(43) "Een direct aanspreekpunt voor al uw vragen."
}
[2]=>
object(stdClass)#781 (2) {
["ID"]=>
string(1) "3"
["Value"]=>
string(20) "Een stabiel netwerk."
}
[3]=>
object(stdClass)#782 (2) {
["ID"]=>
string(1) "4"
["Value"]=>
string(43) "Uw belangrijke gegevens optimaal beveiligd."
}
}
The way I tried traversing the array:
$voordelen = json_decode($_POST['voordelen']);
echo var_dump($voordelen);
for ($i = 0; $i < count($voordelen); $i++) {
foreach ($voordelen[$i] as $key => $item) {
$voorArray = array(
"id" => $item->ID,
"item" => $item->Value,
"content_id" => $content->id // variable from code not shown here.
);
}
}
I also tried:
for ($i = 0; $i < count($voordelen); $i++) {
foreach ($voordelen[$i] as $item) {
$voorArray = array(
"id" => $item->ID,
"item" => $item->Value,
"content_id" => $content->id // Variable from code not shown here.
);
}
}
I also tried using $var['value'] instead of $var->value
But now I'm at a loss. Any help would be appreciated.

I think you are making an extra loop, did you try:
foreach ($voordelen as $item) {
$voorArray = array(
"id" => $item->ID,
"item" => $item->Value,
"content_id" => $content->id // Variable from code not shown here.
);
var_dump($voorArray);
}

What's wrong with just looping through it, since $voordelen is already an array:
$voordelen = json_decode($_POST['voordelen']);
foreach( $voordelen as $item )
{
$voorArray = array(
"id" => $item->ID,
"item" => $item->Value,
"content_id" => $content->id
);
// Do something with $voorArray here.
}

Related

Not able to access data inside a PHP array of object

I´m trying to access data inside a object create after a response(from a dafiti server) with no succsess.
Bellow my code:
***$response = Endpoints::order()->getOrder($orderId)->call($client);
$o = $response->getBody();
echo "<pre>";
var_dump($o);
echo "</pre>";
foreach($o as $value => $obj){
$orderId = $obj->Order->OrderID;// tried this way(not working)
$CustomerFirstName = $obj['Order']['CustomerFirstName'];// tried this way(not working)
}******
Bellow the var_dump:
array(1) {
["Orders"]=>
array(1) {
["Order"]=>
array(23) {
["OrderId"]=>
string(7) "8266761"
["CustomerFirstName"]=>
string(6) "sheila"
["CustomerLastName"]=>
string(14) "rocha domingos"
["OrderNumber"]=>
string(10) "4510948375"
["PaymentMethod"]=>
string(22) "braspag_cc_master_card"
["Currency"]=>
string(3) "BRL"
... to be continue.
How can I access the values inside this array?
Your array contains an array of orders inside of the 'Orders' field of the $o array. So you need to iterate over $o['Orders']. Then you'll be able to access your order details.
<?php
$o = [
'Orders' => [
'Order' => [
'OrderId' => '8266761',
'CustomerFirstName' => 'sheila',
'CustomerLastName' => 'rocha domingos',
'OrderNumber' => '4510948375',
'PaymentMethod' => 'braspag_cc_master_card',
'Currency' => 'BRL'
]
]
];
foreach ($o['Orders'] as $order) {
$orderId = $order['OrderId'];
$CustomerFirstName = $order['CustomerFirstName'];
var_dump($orderId); // 8266761
var_dump($CustomerFirstName); // sheila
}

PHP Array, if duplicate id concat values and delete duplicate

I have an array like this
array(2) {
["sys_ID"]=> string(32) "ab0ce921dba8a810f6db3892399619d9" ["sites"]=> array(5) {
[0]=> array(2) {
["sys_ID"]=> string(32) "448ce5a1dba8a810f6db3892399619ba" ["service"]=> string(4) "IDMB" } [1]=> array(2) {
["sys_ID"]=> string(32) "448ce5a1dba8a810f6db3892399619ba" ["service"]=> string(4) "ODMB" } [2]=> array(2) {
["sys_ID"]=> string(32) "598ce5a1dba8a810f6db3892399619bc" ["service"]=> string(4) "IDMB" } [3]=> array(2) {
["sys_ID"]=> string(32) "876ce5a1dba8a810f6db38923996199f" ["service"]=> string(4) "IDMB" } [4]=> array(2) {
["sys_ID"]=> string(32) "876ce5a1dba8a810f6db38923996199f" ["service"]=> string(4) "ODMB" } } }
If there is a duplicate ['sys_ID'] I want to change the first ['service'] => "IDMB,ODMB" then delete the duplicate value so there is only 1. So the above would become
array(2) {
["sys_ID"]=> string(32) "ab0ce921dba8a810f6db3892399619d9" ["sites"]=> array(5) {
[0]=> array(2) {
["sys_ID"]=> string(32) "448ce5a1dba8a810f6db3892399619ba" ["service"]=> string(4) "IDMB,ODMB" } [1]=> array(2) {
["sys_ID"]=> string(32) "598ce5a1dba8a810f6db3892399619bc" ["service"]=> string(4) "IDMB" } [2]=> array(2) {
["sys_ID"]=> string(32) "876ce5a1dba8a810f6db38923996199f" ["service"]=> string(4) "IDMB,ODMB" } ]} }
The first array was made getting POST values;
<?php
foreach ($_POST['services'] as $item) {
$parts = explode(',', $item);
$siteID = $parts[1];
$services = $parts[0];
$data['sites'][] = [
'sys_ID' => $siteID,
'service' => $services
];
}
?>
Change the way you generate your array to something like this:
<?php
$data = [
'sites' => [],
];
foreach ($_POST['services'] as $item) {
// Gather your data
$parts = explode(',', $item);
$siteID = $parts[1];
$services = $parts[0];
// Set flag to remember whether you need to add it
$add = true;
// Loop through existing data and check if the sys_ID already exists
foreach ($data['sites'] as &$dataDetails) {
// It does ... so just append your service
if ($dataDetails['sys_ID'] === $siteID) {
$add = false;
$dataDetails['service'] .= ',' . $services;
break;
}
}
// Couldn't find the sys_ID => Add new entry
if ($add) {
$data['sites'][] = [
'sys_ID' => $siteID,
'service' => $services
];
}
}
?>
It will be better to fill the array properly from the beginning; however I will still post a solution. We have the array defined like this:
$arr = array(
'sys_ID' => 'ab0ce921dba8a810f6db3892399619d9',
'sites' => array(
0 => array(
'sys_ID' => "448ce5a1dba8a810f6db3892399619ba",
'service'=> "IDMB"
),
1 => array(
'sys_ID' => "448ce5a1dba8a810f6db3892399619ba",
'service'=> "ODMB"
),
2 => array(
'sys_ID'=> "598ce5a1dba8a810f6db3892399619bc",
'service'=> "IDMB"
),
3 => array(
'sys_ID'=> "876ce5a1dba8a810f6db38923996199f",
'service'=> "IDMB"
),
4 => array(
'sys_ID'=> "876ce5a1dba8a810f6db38923996199f",
'service'=> "ODMB"
)
)
);
To merge the elements like described, you can do the following loop:
// For each site (1)...
for($i=0; $i<count($arr["sites"])-1; $i++){
// Take each of sites starting from the next one to the end (2)
for($j=$i+1; $j<count($arr["sites"]); $j++){
// If there is a match in sys_ID beteen (1) and (2)
if($arr["sites"][$i]['sys_ID'] == $arr["sites"][$j]['sys_ID']){
// Merge the service into (1) with comma separation
$arr["sites"][$i]['service'] = $arr["sites"][$i]['service'].",".$arr["sites"][$j]['service'];
// then delete (2)
array_splice($arr["sites"],$j,1);
$j--;
}
}
}
Note that this will reindex the numebers (1,2,3...). If you wish to preserve them, you can use unset() instead.

What is the best way to group a php array?

For example, I have this array:
$bills = array(
array("bill_id"=>"1", "product_id"=>"1", "total"=>"10"),
array("bill_id"=>"2", "product_id"=>"2", "total"=>"20"),
array("bill_id"=>"3", "product_id"=>"1", "total"=>"30"),
array("bill_id"=>"4", "product_id"=>"1", "total"=>"40"),
array("bill_id"=>"5", "product_id"=>"2", "total"=>"50")
);
We need to add the totals of each produdct into a single array, i.e. What is the best clean fast way to generate the following array from the above one:
$products = array(
array("product_id"=>"1", "total"=>"80"),
array("product_id"=>"2", "total"=>"70")
);
the fastest way to sum this is index array, something like this
$products = array();
foreach ($bills as $bill) {
$key = $bill['product_id'];
if (isset($products[$key])) {
$products[$key]['total'] += $bill['total'];
} else {
$products[$key] = $bill;
}
}
var_dump($products);
output
array(2) {
[1]=>
array(3) {
["bill_id"]=>
string(1) "1"
["product_id"]=>
string(1) "1"
["total"]=>
int(80)
}
[2]=>
array(3) {
["bill_id"]=>
string(1) "2"
["product_id"]=>
string(1) "2"
["total"]=>
int(70)
}
}
to browse the invoice list
foreach($products as $key=>$bill) {
var_dump($bill);
}
Thie simplest approach is a single-pass loop.
$byProduct = [];
foreach($bills as $bill)
{
$key = $bill['product_id'];
if (!isset($byProduct[$key])) {
$byProduct[$key] = [
'product_id' => $key,
'total' => 0
];
}
$byProduct[$key]['total'] += $bill['total'];
}
Result of var_dump($byProduct):
array(2) {
[1] =>
array(2) {
'product_id' =>
string(1) "1"
'total' =>
int(80)
}
[2] =>
array(2) {
'product_id' =>
string(1) "2"
'total' =>
int(70)
}
}
Another approach is to use array_walk but it is pretty much the same in terms of complexity:
$byProduct = [];
array_walk($bills, function(&$bill) use (&$byProduct) {
$key = $bill['product_id'];
if (!isset($byProduct[$key])) {
$byProduct[$key] = [
'product_id' => $key,
'total' => 0
];
}
$byProduct[$key]['total'] += $bill['total'];
});

Combining array values for the same associative key

I've got this array, and I want to loop through it and add up the values prices that are on the same OrderDate. The other values like the Discount code I want to add as a sub-array.
array(3) {
[0]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
NULL
["TotalRevenue"]=>
string(9) "147618.76"
["Discount_Revenue"]=>
string(8) "13453.77"
}
[1]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
string(6) "SALE38"
["TotalRevenue"]=>
string(8) "364.92"
["Discount_Revenue"]=>
string(8) "4083.64"
}
[2]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
string(9) "WELCOME20"
["TotalRevenue"]=>
string(6) "113.83"
["Discount_Revenue"]=>
string(6) "113.83"
}
}
So it should then look like:
array(3) {
[0]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCodes"]=> array {
[0] => "DISCOUNT"
[1] => "SALE38"
[2] => "WELCOME20"
)
["TotalRevenue"]=>
string(9) "147618.76"
["Discount_Revenue"]=>
string(8) "13453.77"
}
}
I believe I have fixed it using this loop adding to the array if the key exists. Not sure if this is the most efficient way to do it though?
foreach ($results as $k => $result){
if( array_key_exists($result['OrderDate'], $arr)){
$arr[$result['OrderDate']]['price'] += $result['TotalRevenue'];
$arr[$result['OrderDate']]['new'] = false;
} else {
$arr[$result['OrderDate']] = array(
'price' => $result['TotalRevenue'],
'new' => true
);
}
}
I've come to my own solution if anyone else needs it.
$arr = array();
foreach ($results as $k => $result){
if( array_key_exists($result['OrderDate'], $arr)){
$arr[$result['OrderDate']]['Total_Revenue'] += $result['TotalRevenue'];
$arr[$result['OrderDate']]['Discount_Revenue'] += $result['Discount_Revenue'];
isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
$arr[$result['OrderDate']]['new'] = false;
} else {
$arr[$result['OrderDate']] = array(
'Total_Revenue' => $result['TotalRevenue'],
'Discount_Revenue' => $result['Discount_Revenue'],
'new' => true
);
isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
}
}

Building an array in PHP with Codeigniter

I'm trying to build an array in Codeigniter 3, but I cant seem to structure it properly.
I have 2 tables that I basically need to combine; questions and their associated answers.
SO, basically I need a multidimensional array, each inner array is to contain the question data along with its associated answer data.
This is what I'm doing at the moment:
$question_array = array();
foreach($course_object->result() as $question){
$question_array[] = array (
'question_id' => $question->question_id,
'question' => $question->question,
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$question_array[]['answer'] = $answer->answer;
$question_array[]['result'] = $answer->result;
}
}
return $question_array;
But that outputs each question as an array on its own, as well as each answer, i need to combine them somehow. This is what I'm getting:
array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
}
array(1) {
["answer"]=>
string(11) "The Manager"
}
array(1) {
["result"]=>
string(1) "0"
}
array(1) {
["answer"]=>
string(18) "The Fire Authority"
}
array(1) {
["result"]=>
string(1) "1"
}
and this is what i need:
array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
["answer"]=>
string(11) "The Manager"
["result"]=>
string(1) "0"
["answer"]=>
string(18) "The Fire Authority"
["result"]=>
string(1) "1"
}
I've tried things like array_push but I cant seem to get it to work?
Any ideas what I can try?
The easiest way to do it is to create a new array with what you need, and append it to the $question_array, like this. You'll need a new subarray for the answers, because you can't have duplicate keys in an array.
foreach($course_object->result() as $question){
$q_array = array (
'question_id' => $question->question_id,
'question' => $question->question,
'answers' => array()
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$q_array['answers'][] = array(
'answer' => $answer->answer,
'result' =>$answer->result
);
}
$question_array[] = $q_array;
}
I think this should work.
$question_array = array();
$i = 0;
foreach($course_object->result() as $question){
$question_array[$i] = array (
'question_id' => $question->question_id,
'question' => $question->question,
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$question_array[$i]['answer'][] = $answer->answer;
$question_array[$i]['result'][] = $answer->result;
}
$i++;
}
return $question_array;

Categories