Issues creating an associative array with another array in PHP - php

I'm trying to create an associative array in PHP using an Object. The Object is values from a database, called Category. It only has two values, an id and a name field.
This is what I have:
$category = $em->getRepository('AppBundle:Category')->findAll();
$stuff = array();
foreach($category as $cat) {
$stuff[$cat->getName()] = $stuff[$cat->getId()];
}
But I get this nasty error:
Notice: Undefined offset: 1
I should say that I am using Symfony 3. Any help would be great.

You're on the right track but you need to remove echo since you're not trying to output anything. You're also attempting to assign a value from the array you're trying to enter a value into.
$stuff[ $cat->getName() ] = $cat->getId();

Sorry I just omitted the value and replace with $cat->getId() in stead of $stuff[$cat->getId()] and it worked

You $stuff array has no index 1, so it will cause that issue.
This is caused by $stuff[$cat->getId()];, which should be $cat->getId();
foreach($category as $cat) {
$stuff[$cat->getName()] = $cat->getId();
}

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.

How to get array values without forloop?

I have a json_decode array which I can access the values fine with a foreach like this :
foreach ($prodvariants["result"]["sync_variants"] as $variant) {
echo $product_name = $variant['product']['name'];
}
This works great.
But what if I do not want a foreach? How can I access the same values but without the forloop?
I tried this
$variant =$prodvariants["result"]["sync_variants"];
echo $product_name = $variant['product']['name'];
But when I try it like this,without the foreach I get error
Notice: Undefined index: product
You missed one key there.
echo $product_name = $variant[0]['product']['name'];
^^^
If JSON has numeric keys, it will be [0]. If you're using another keys, just change it.
But without any loop (for, foreach, while) you can't access to all variants in one line of code. You can choose just a single record. It's a non-sense to get loop out.

PHP function Get the current key and value inside an array, array to string conversion error

I have the following function which gets some data from DB table.
Now I realize this question must have been asked many times before but I refer you to this link which is the top result for problem Im having. Get the current key and value inside an array
When I call my function and do a var_dump(LoadBoxes()) all is well no problems, thus my function is working correctly as can be seen from the image below:
However when I try to get the array keys and values as pointed out by top linked question I get the following error:
Notice: Array to string conversion in
C:\xampp\htdocs\beta\xxxx\xxxx_letsGo.php on line 25 0 Array
So clearly I must be doing something wrong any help appreciated, code follows:
function LoadBoxes()
{
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$data[] = array(
'LowHeadline' => $box['lowHeadline'],
'MediumHeadline' => $box['mediumHeadline'],
'HighHeadline' => $box['highHeadline'],
'Low' => $box['BoxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $data;
//call function
$boxesInfo = LoadBoxes();
foreach($boxesInfo as $arrayKey => $info) {
echo $arrayKey.' '.$info;
}
Ive tried using LoadBoxes() function instead of assigning it to variable $boxesInfo[] inside foreach loop, same result. Ive pretty much tried everything to best of my knowledge any help appreciated.
Additional Info
It is only when I explicitly call the array key inside foreach() that I get result back like such:
foreach($boxesInfo as $arrayKey => $info) {
echo $boxesInfo['LowHeadline'] // returns LOW RISK
}
The problem is with [] in $boxesInfo[] = LoadBoxes(); Your function LoadBoxes() returns an array of boxinfo, and you assign that to an array. So the loop just sees an array with one element, which is itself another array. If you change the line to $boxesInfo = LoadBoxes(); you should get the expected result.
On second thought, loadBoxes() returns an array of boxes, which are themselves arrays, so you would need nested loops to get the info of all boxes:
foreach($boxesInfo as $box) {
foreach($box as $arrayKey => $info) {
echo $arrayKey.' '.$info;
}
}

Trying to create an associative array PHP

I have the following array. What I'm trying to do is get each element under "bill_ids", use the ID (e.g. "hjres61-114") to make another call and then retitle the 0 under "bill_ids" to the ID and then include another array under that element.
Here's what I have and it's giving me this error..
Message: Illegal offset type
$floor_updates = $this->congress->floor_updates($params);
foreach ($floor_updates as $update) {
if ($update['bill_ids']) {
foreach ($update['bill_ids'] as $bill => $bill_id) {
$billInfo = $this->bill->billSearch(['bill_id' => $bill_id]);
$floor_updates[$update]['bill_ids'][$bill][0] = $billInfo;
}
}
}
I'm terrible with php arrays and any guidance would be greatly appreciated..
What you actually want to do is the following:
First, capture the array index of each of our update elements. We can simply do that by passing in $array_index => $update.
foreach ($floor_updates as $array_index => $update)
Now, we can access the $update array by $floor_updates[$array_index].
$floor_updates[$array_index]['bill_ids'][$bill] = $billInfo;
In the above, there's no reason to access the 0th element of the array as the $bill actaully contains reference to the index of each key value pair, so we can simply just reference [$bill] to get access to the array.

Foreach() value is set, after value disappears

I am trying to add a new key to an existing numerical indexed array using a foreach() loop.
I wrote this piece of code:
foreach($new['WidgetInstanceSetting'] as $row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
The first debug() works as I expected: the 'random_key' is created in the $new array.
Now, the problem is that the second debug() shows the $new array, but without the newly added key.
Why is this happening? How can I solve this problem?
$row ends up being a copy in the scope of the foreach block, so you really are modifying a copy of it and not what's in the original array at all.
Stick a & in your foreach to modify the $row array within your $new array by reference:
foreach($new['WidgetInstanceSetting'] as &$row){
And as user576875 says, delete the reference to $row in case you use that variable again to avoid unwanted behavior, because PHP leaves it around:
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
unset($row);
debug($new);
Use the & to get a by reference value that you can change.
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
You need to access the element by reference if you want to modify if within the array, as follows:
foreach($new['WidgetInstanceSetting'] as &$row) {
$row['random_key'] = $this->__str_rand(32, 'alphanum');
}
you are not creating random_key in $new array you are creating it in $row

Categories