Trying to create an associative array PHP - 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.

Related

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;
}
}

PHP Loop array object once, or wild card key?

I have a php array, and inside the array is a reference to another php object with a numerical value.
How can i access the elements in this array without knowing that numerical id (it could be different for each array)?
In the image below, I need to get the values inside field_collection_item like so....
$content['field_image_columns'][0]['entity']['field_collection_item'][133]['field_image']
For the first array key (0) i have done the following...
$i = 0;
while($i <= 2) {
if(isset($content['field_image_columns'][$i])) {
print '<div class="column-' . $i . '">';
foreach ($content['field_image_columns'][$i]['entity']['field_collection_item'] as $fcid => $values) {
// Print field values
}
print '</div>';
}
$i++;
}
Doing a foreach loop for a single array item seems wrong - is there a method i should be using for this use case?
You can select first item of array for example with:
Use array_shift, but it will modify source array:
$cur = array_shift($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
Get keys of array with array_keys and use first element of result as a key
$ks = array_keys($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $content['field_image_columns'][$i]['entity']['field_collection_item'][$ks[0]]['field_image'];
Use current function:
$cur = current($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
As with most programming, there are quite a few ways you could do it. If a foreach works, then it isn't wrong, but it may not be the best way.
// Get the current key from an array
$key = key($array);
If you don't need the key, then you can just get the value from the array.
// Get the current value from an array
$value = current($array);
Both of these will retrieve the first key/value from the array assuming you haven't advanced the pointer.
current, key, end, reset, next, & prev are all array functions that allow you to manipulate an array without knowing anything about the internals. http://php.net/manual/en/ref.array.php

Issues creating an associative array with another array in 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();
}

increment value inside an array of arrays (if key is non-existent, set it to 1)

Question has been updated to clarify
For simple arrays, I find it convenient to use $arr[$key]++ to either populate a new element or increment an existing element. For example, counting the number of fruits, $arr['apple']++ will create the array element $arr('apple'=>1) the first time "apple" is encountered. Subsequent iterations will merely increment the value for "apple". There is no need to add code to check to see if the key "apple" already exists.
I am populating an array of arrays, and want to achieve a similar "one-liner" as in the example above in an element of the nested array.
$stats is the array. Each element in $stats is another array with 2 keys ("name" and "count")
I want to be able to push an array into $stats - if the key already exists, merely increment the "count" value. If it doesn't exist, create a new element array and set the count to 1. And doing this in one line, just like the example above for a simple array.
In code, this would look something like (but does not work):
$stats[$key] = array('name'=>$name,'count'=>++);
or
$stats[$key] = array('name'=>$name,++);
Looking for ideas on how to achieve this without the need to check if the element already exists.
Background:
I am cycling through an array of objects, looking at the "data" element in each one. Here is a snip from the array:
[1] => stdClass Object
(
[to] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[name] => foobar
[id] => 1234
)
)
)
I would like to count the occurrences of "id" and correlate it to "name". ("id" and "name" are unique combinations - ex. name="foobar" will always have an id=1234)
i.e.
id name count
1234 foobar 55
6789 raboof 99
I'm using an array of arrays at the moment, $stats, to capture the information (I am def. open to other implementations. I looked into array_unique but my original data is deep inside arrays & objects).
The first time I encounter "id" (ex. 1234), I'll create a new array in $stats, and set the count to 1. For subsequent hits (ex: id=1234), I just want to increment count.
For one dimensional arrays, $arr[$obj->id]++ works fine, but I can't figure out how to push/increment for array of arrays. How can I push/increment in one line for multi-dimensional arrays?
Thanks in advance.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
// this next line does not meet my needs, it's just to demonstrate the structure of the array
$stats[$obj->id] = array('name'=>$obj->name,'count'=>1);
// this next line obviously does not work, it's what I need to get working
$stats[$obj->id] = array('name'=>$obj->name,'count'=>++);
}
Try checking to see if your array has that value populated, if it's populated then build on that value, otherwise set a default value.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
if (!isset($stats[$obj->id])) { // conditionally create array
$stats[$obj->id] = array('name'=>$obj->name,'count'=> 0);
}
$stats[$obj->id]['count']++; // increment count
}
$obj = $element->to->data is again an array. If I understand your question correctly, you would want to loop through $element->to->data as well. So your code now becomes:
$stats = array();
foreach ($dataArray as $element) {
$toArray = $element->to->data[0];
foreach($toArray as $toElement) {
// check if the key was already created or not
if(isset($stats[$toElement->id])) {
$stats[$toElement->id]['count']++;
}
else {
$stats[$toElement->id] = array('name'=>$toArray->name,'count'=>1);
}
}
}
Update:
Considering performance benchmarks, isset() is lot more faster than array_key_exists (but it returns false even if the value is null! In that case consider using isset() || array_key exists() together.
Reference: http://php.net/manual/en/function.array-key-exists.php#107786

PHP json_decode array cannot retrieve numerical index?

I have an array that is associative that I have decoded from a json json_decode second value true and looks like
Array (
[test] => Array
(
[start] => 1358766000
[end] => 1358775000
[start_day] => 21
[end_day] => 21
)
)
But for some reason when I do $array[0] I get null? How can I get the array by index? Not by key name?
array_values() will give you all the values in an array with keys renumbered from 0.
The first level of the array is not numerical, it's an associative array. You need to do:
$array['test']['start']
Alternatively, to get the first element:
reset($array);
$first_key = key($array);
print_r($array[$first_key]);
You could use current.
$first = current($array); // get the first element (in your case, 'test')
var_dump($first);
This is by design . . . your JSON used a key (apparently test), which contained a JSON object. The keys are preserved when you do a json_decode. You can't access by index, though you could loop through the whole thing using a foreach.
From your comment, it sounds like you want to access previous and next elements from an associative array. I don't know a way to do this directly, but a hackish way would be as follows:
$testArr = array('a'=>'10', 'b'=>'2', 'c'=>'4');
// get numeric index of the element of interest
$keys = array_keys($testArr);
$i = array_search('b', $keys);
// get key of next element
$nextElementKey = $keys[$i+1];
// next element value
$nextElementValue = $testArry[$nextElementKey];
// get key of previous element
$prevElementKey = $keys[$i-1];
// prev value
$[prevElementValue = $testArry[$prevElementKey];
You'd probably want to add some error checking around the previous and next key calculations to handle the first and last values.
If you don't care about the data in the key, Ignacio's solution using array_keys is much more efficient.

Categories