PHP: 2D array create index or add if exists - php

Ok, long story short: I am trying to place items in an array sorted by a value as part of an object(the object defined as $aProductOrdered and the public value:productMan). The post will be variable depending on items added and removed from a database so it has to be dynamic.
For example if the index is 12 for a certain productMan value all items with that would be in one row like:
[12][0]:prodObj [12][1]:prodObj
[15][0]:prodObj
[22][0]:prodObj [22][1]:prodObj
where the first is the prodMan value from the object and the second is an arbitrary auto assigned index to loop through representing each object.
Below is what I have but when I go to insert into the array, it accurately says the index I am trying to add to is undefined. How may I add the index if it doesn't exist or if it does just append to it?
$vendOrderArray = array(array());
//here we will loop through all non blank posted orders and create objects to place them in our $orderArray
foreach($_POST as $prodID=>$numOrderded)
{
if(is_numeric($numOrderded) && $numOrderded != "" && $numOrderded != "0")
{
$aProductOrdered = getProduct($prodId);
$aProductOrdered->numberOrdered = $numOrderded;
array_push($vendOrderArray[$aProductOrdered->productMan],$aProductOrdered);
}
}

if(!isset($vendOrderArray[$aProductOrdered->productMan]))
$vendOrderArray[$aProductOrdered->productMan] = array();
Just before the array_push call.

Related

Foreach loop over array of objects Laravel

I'm receiving this array of objects and need to iterate over it, but the problem is that I need to get the value of the next item when its iterating, to compare the value of the current object with the next one, and if it's a different value, split this array in two.
So, I was doing it with next() php function:
//looking for the next register in the array
$next = next($finances);
//first array if exist different values
$aiuaEd = [];
//second array if exist different values
$aiua = [];
foreach ($finances as $finance) {
if ($finance->cnpj <> $next->cnpj) {
$aiua[] = $finance;
} else {
$aiuaEd[] = $finance;
}
}
This code works fine at some point, but then I got this error:
Trying to get property 'cnpj' of non-object in
I don't know why sometimes works well and sometimes don't, debugging this variables, I found that if my array have 2 objects inside only, when I'm looping over it, the $next->cnpj variable came as empty, and sometimes don't.
Can someone help me with this?
I solved it with a different approach, instead of using php next(), I first loop over this array saving the cnpj's into an array.
$cnpjs = [];
foreach($finances as $finance){
$cnpj[] = $finance->cnpj;
}
Then I use array_unique() to group this 2 differents CNPJ's and sort() to get the correct keys order.
//grouping cnpjs as unique, should exist only 2 keys
$cnpj = array_unique($cnpj);
//sort array keys to get in order
sort($cnpj);
Then I iterate over my $finances array again, but now I'm counting if this $cnpj array has more than 2 positions, which means that I have to split this data in two differents arrays.
foreach($finances as $finance){
if(count($cnpj) > 1){
if($finance->cnpj == $cnpj[1]){
$aiua[] = $finance;
}else{
$aiuaEd[] = $finance;
}
}else{
$aiuaEd[] = $finance;
}
}
I'm pretty sure that this is not the best approach for that problem, or at least the most optimized one, so I'm open for new approach's suggestions!
Just posting how I solved my problem in case anyone having the same one.
Notice that this approach is only usable because I know that will not exist more than 2 different's CNPJ's in the array.

Conditional unset from Guzzle response

I've seen a few questions and the ones worth referencing
How can i delete object from json file with PHP based on ID
How do you remove an array element in a foreach loop?
How to delete object from array inside foreach loop?
Unset not working in multiple foreach statements (PHP)
The last two from the list are closer to what I'm intending to do.
I've got a variable names $rooms which is storing data that comes from a particular API using Guzzle
$rooms = Http::post(...);
If I do
$rooms = json_decode($rooms);
this is what I get
If I do
$rooms = json_decode($rooms, true);
this is what I get
Now sometimes the group exists in the same level as objectId, visibleOn, ... and it can assume different values
So, what I intend to do is delete from $rooms when
group isn't set (so that specific value, for example, would have to be deleted)
group doesn't have the value bananas.
Inspired in the last two questions from the initial list
foreach($rooms as $k1 => $room_list) {
foreach($room_list as $k2 => $room){
if(isset($room['group'])){
if($room['group'] != "bananas"){
unset($rooms[$k1][$k2]);
}
} else {
unset($rooms[$k1][$k2]);
}
}
}
Note that $room['group'] needs to be changed to $room->group depending on if we're passing true in the json_decode() or not.
This is the ouput I get if I dd($rooms); after that previous block of code
Instead, I'd like to have the same result that I've shown previously in $rooms = json_decode($rooms);, except that instead of having the 100 records it'd give only the ones that match the two desired conditions.
If I am not totally wrong, then this should do the trick for you:
$rooms = json_decode($rooms);
$rooms->results = array_values(array_filter($rooms->results, function($room) {
return property_exists($room, 'group') && $room->group != "banana";
}));
Here is a verbose and commented version of this one above:
$rooms = json_decode($rooms);
// first lets filter our set of data
$filteredRooms = array_filter($rooms->results, function($room) {
// add your criteria for a valid room entry
return
property_exists($room, 'group') // the property group exists
&& $room->group == "banana"; // and its 'banana'
});
// If you want to keep the index of the entry just remove the next line
$filteredRooms = array_values($filteredRooms);
// overwrite the original results with the filtered set
$rooms->results = $filteredRooms;

Change variable value inside an array in a new array

How to, and is it possible to add different value to a variable inside an array, but to simplify it possibly to do it with another array; i need to store processes and their cpu load on my page, but since process names are "ugly", i need to change their name to something normal looking
so far i have managed to extract top 5 of them (mostly the same every time) like this:
$array[0] = "process1";
$array[1] = "process2";
$array[2] = "process3";
Now i want to add as many possibilities as possible to change some prettier values to them
$new_values = array(
"process1" == "Process name as i want it",
"process2" == "Second process"
);
So when i call say $array[1]
i don't get "process2" but changed name ("Second process")
Thanks in advance
You could do something like this, using the value from the first array as the key for the $new_values array:
echo $new_values[$array[1]]; // Second process
Edit: I'll wrap this inside a function to check for the $new_values existence, otherwise fall back to the original value:
function displayPretty($key) {
global $new_values; // get the $new_values array from global scope
if(array_key_exists($key, $new_values))
return $new_values[$key]; // return pretty name if it exists
return $key; // return original value otherwise
}
echo displayPretty($array[1]);
This way, if you pass in $array[1] it will return the value from $new_values if it exists (e.g. Second process in this case), and if it doesn't (e.g. if you passed in $array[5] and that doesn't have a pretty definition in $new_values) it will just return what you passed in.

PHP spontaneously creates associative array where indexed array is required - using PHP arrays with Highcharts

I'm using PHP to retrieve data from an SQL database to produce a stacked column chart in Highcharts. The idea is that I'm taking the following piece of code to retrieve values from my database. This code should generate an array which then gets encoded to JSON and passed to Highcharts; this code produces a single 'part' of a stacked column, and the index determines which vertical bar that part is in. (So in http://www.highcharts.com/demo/column-stacked, the index would represent which fruit, and the data in this series would represent one person/color.)
The issue is that when I run this code, instead of ending up with an indexed array of data grouped by category, such as
[12,13,14,15] where each item is a category, I end up with an associative array where the indexes I specified in the code are turned into a string key.
{"1":13,"0":12,"3":14, "2":13, "5":15}
Because my indexes are being interpreted as associative keys and not as the indexed locations of the data inside the array, the data is now being added to locations in the order that I retrieved the data, and not assigned to a location in the array based on the index I give. Highcharts assigns categories based on location in the array, and not on key, so all my data ends up in the wrong categories.
Is there a way to get PHP to treat my carefully collected indexes as indexes and not as keys, and add my data points in the location in the array indicated by the indexes? I'm kind of new to PHP, and Java and C++ - the languages I've worked with before - don't have associative arrays, so any help you can give me in explaining and fixing this undesired behavior would be much appreciated.
Code below.
$variable indicates what the data is being sorted into categories by, and $r is the variable representing the array of the SQL query, so $r['variable'] is the category of this data point, and $r['amount'] is the data point itself.
$found = -1;
//if this is the first set of data being collected
if (count($category['data']) == 0){
$category['data'][0] = $r[$variable];
$series1['data'][0] = floatval($r['amount']);
$count++;
$times1[0]++;
}
//if it's not the first set of data, find out if this category has been used before
else {
for ($x = 0; $x < count($category['data']); $x++){
if ($r[$variable] == $category['data'][$x]){
$found = $x;
break;
}
}
// if that category does not already exist, add it, and add the data
if ($found == -1) {
$times1[$count]++;
$category['data'][$count] = $r[$variable];
$series1['data'][$count] = floatval($r['amount']);
$count++;
}
else { //otherwise, add its data to the data already in the current category. This will eventually yield an average, with $times1[] as the divisor
$times1[$found]++;
$series3['data'][$found] = floatval((floatval($series3['data'][$found]) + floatval($r['amount'])));
}}
Go through with below code hope it will give some idea to resolve your problem --
<?php
$jsonstring = '{"1":13,"0":12,"3":14, "2":13, "5":15}';
$tempArr = json_decode($jsonstring, true);
asort(tempArr); // for sorting the array --
//run another foreach to get created an array --
$finArr = array();
foreach(tempArr as $key=>$val){
$finArr[] = $val;
}
$requiredjsonString = json_encode(finArr); // it will return your required json Array [12,13,14,15]
?>
Edit: I advice also set JSON_NUMERIC_CHECK flag in json_encode();

Assign values to an associated array in a loop

I am having a difficult time creating an associated array and assigning a value to the key. I have two arrays (tech_pay and tech_scans) and I am doing a simple calculation using their values and I want to create a new array called tech_per_scan but I keep getting an array with the key automatically created starting at 0.
$tech_per_scan = array();
foreach($tech_pay as $key=>$value)
{
$pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan
$tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan);
}
This line $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); will add an element to you array and it will start with 0 as its index, because you did not specify its key. Similar to array_push
It should be $tech_per_scan[$id]
$tech_per_scan[$id] = $pay_per_scan;
you should set value for new array like this :
$tech_per_scan[$key] = $pay_per_scan ;
Full code is :
$tech_per_scan = array();
foreach($tech_pay as $key=>$value)
{
$pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan
$tech_per_scan[$key] = $pay_per_scan ;
}

Categories