Dynamic array index in PHP - php

I don't know why I'm having trouble figuring this out, but I'm hoping someone can help.
I want to dynamically add multiple indices to an array. For example, if I have a list of IDs.
$ids = array(1247, 1248);
How can I do this dynamically, depending on the number of ids that are in the array?
$history['transactions'][$id1][$id2]['Thursday'] = 0;

If I am unserstanding you correctly, then your code should work. unless you are trying to use the array your created, take a look. I think a simple change could solve your problem
this would work:
$ids = array(1247, 1248);
$history['transactions'][$ids[0]][$ids[1]]['Thursday'] = 0;
So would this:
$id1 = 1247;
$id2 = 1248;
$history['transactions'][$id1][$id2]['Thursday'] = 0;
From the looks of it, you just aren't calling anything. but without more of your code I can't be more help
As Daedalus points out, to this point the code isn't really dynamic, (I assumed you just needed a snipit in the the middle to help with already dynamic code. but now I will assume the opposite) here is an example of how how to change that:
say you had the array $ids = array(1247, 1248, 1249, 1250, 1251); you would need to loop through the lot of them and deal with them individually. Probably the easiest way to do that would be something like:
$ids = array(1247, 1248, 1249, 1250, 1251);
foreach($ids as $id){
$history['transactions'][$id]['Thursday'] = 0;
}
Make sense?
Third try:
Getting a better understanding of whats going on. (sorry, took a long time to get it through my thick skull)
So if you want an array with all the ids in order of the array $ids = array(1247, 1248, 1249, 1250, 1251); then this is the solution for you:
$ids = array(1247, 1248, 1249, 1250, 1251);
$result = array('Thursday' => 0);
for($i = count($ids) -1; $i >= 0; $i--){
$result = array($ids[$i] => $result);
}
$history = array('transactions' => $result);
var_dump($history) yields:
array(1) {
["transactions"]=>
array(1) {
[1247]=>
array(1) {
[1248]=>
array(1) {
[1249]=>
array(1) {
[1250]=>
array(1) {
[1251]=>
array(1) {
["Thursday"]=>
int(0)
}
}
}
}
}
}
}
Which is now what I believe you are looking for

I think that if you explain better what's your problem, we could help in a better way that explaining you how to create arrays like this:
$history['transactions'][$id1][$id2]['Thursday'] = 0;
depending on how much ids there are in a array. For sure you can do what you want do to in a better way.
Or, just try to think some other way than putting ids as parameters of an array.

You could use references to achieve this very dynamically, but I don't understand the reason to do this...
$ids = array(1247, 1248);
$data = &$history['transactions'];
foreach ($ids as $id) {
$data = &$data[$id];
}
$data['Thursday'] = 0;

Related

for loop and appending to an array in PHP

I have the following code:
$items = array();
foreach($following as $storeOwner)
{
array_push($items, $productRepository->mostRecentItem($storeOwner->getId(), 5));
}
I am trying to append the results of
$productRepository->mostRecentItem($storeOwner->getId(), 5)
to $items. How do I do so? Why doesn't the above code work?
Try this:
$items = array();
foreach($following as $storeOwner)
{
$items[] = $productRepository->mostRecentItem($storeOwner->getId(), 5);
}
Also, take a look to the result of the mostRecentItem Method... .
var_dump you different objects and return values to make sure that contain what you think they should contain. The code looks "correct" so it's probably the objects and values that are not.

Accessing an array in an object

If i knew the correct terms to search these would be easy to google this but im not sure on the terminology.
I have an API that returns a big object. There is one particular one i access via:
$bug->fields->customfield_10205[0]->name;
//result is johndoe#gmail.com
There is numerous values and i can access them by changing it from 0 to 1 and so on
But i want to loop through the array (maybe thats not the correct term) and get all the emails in there and add it to a string like this:
implode(',', $array);
//This is private code so not worried too much about escaping
Would have thought i just do something like:
echo implode(',', $bug->fields->customfield_10205->name);
Also tried
echo implode(',', $bug->fields->customfield_10205);
And
echo implode(',', $bug->fields->customfield_10205[]->name);
The output im looking for is:
'johndoe#gmail.com,marydoe#gmail.com,patdoe#gmail.com'
Where am i going wrong and i apologize in advance for the silly question, this is probably so newbie
You need an iteration, such as
# an array to store all the name attribute
$names = array();
foreach ($bug->fields->customfield_10205 as $idx=>$obj)
{
$names[] = $obj->name;
}
# then format it to whatever format your like
$str_names = implode(',', $names);
PS: You should look for attribute email instead of name, however, I just follow your code
use this code ,and loop through the array.
$arr = array();
for($i = 0; $i < count($bug->fields->customfield_10205); $i++)
{
$arr[] = $bug->fields->customfield_10205[$i]->name;
}
$arr = implode(','$arr);
This is not possible in PHP without using an additional loop and a temporary list:
$names = array();
foreach($bug->fields->customfield_10205 as $v)
{
$names[] = $v->name;
}
implode(',', $names);
You can use array_map function like this
function map($item)
{
return $item->fields->customfield_10205[0]->name;
}
implode(',', array_map("map", $bugs)); // the $bugs is the original array

While script inside of an array

pretty straight forward question this - I am trying to create an array to store the Model and Cost values taken from my database table. I figured I could begin the array, then create a while loop, and then end the array, and smiles all around. I may be mistaken, or I may have blindly missed something in my code, but could you have a look?
$array = array(
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$overall_cost["model"] => $overall_cost["cost"],
}
);
var_dump($array);
I think this is what you're looking for:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);
You can't do it like this. You need to add to the array inside the while loop:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);
would be one way of doing it.
EDITED to produce simple array.
I don't think that will work. Try something like:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);

Select value out of array in PHP

Ok, so I have this in a JSON array (the output of retrievedData())
{
"device": {
"01AA02AB141208VV": {
"$version": -148598935,
"$timestamp": 1344382016000,
"serial_number": "01AA02AB141208VV"
}
}
}
However, I can't seem to select the serial number. I have tried what usually works, but I can't select it. This is assuming we don't already know the "01AA02AB141208VV".
$retrieved_data = retrieveData($array['userid'], $array['urls']['transport_url'], $array['access_token']);
$retrieved_data_array = json_decode($retrieved_data, true);
$serial_number = $retrieved_data_array['device'][0]['serial_number'];
Am I doing something wrong? I bet it's really simple, but I just cannot figure it out!
Thanks!
Unfortunately, it's not really simple. You're trying to find 42 Main St. when you don't know the city Main St. is located in. The only way to find the serial_number would be to loop over $retrieved_data_array with foreach until you find the value you want.
you can use key() function to access the keys of the associative array (in this case the '$retrieved_data_array['device']' array:
<?php
$data = '{"device": {"01AA02AB141208VV": {"$version": -148598935,"$timestamp": 1344382016000,"serial_number": "01AA02AB141208VV"}}}';
$retrieved_data_array = json_decode($data, true);
$serial_number = key($retrieved_data_array['device']);
reset($retrieved_data_array['device']);
print_r($serial_number);
print_r($retrieved_data_array['device'][$serial_number]);
?>
This will grab the serial numbers, assuming you have multiple items in the devices array:
$keys = array();
foreach( $retrieved_data_array['device'] as $key => $val ){
$keys[] = $key;
}
$serial = $keys[0];
This can be reduced if you know you only have one item in the array...

How would I loop through this?

I have a large array.
In this array I have got (among many other things) a list of products:
$data['product_name_0'] = '';
$data['product_desc_0'] = '';
$data['product_name_1'] = '';
$data['product_desc_1'] = '';
This array is provided by a third party (so I have no control over this).
It is not known how many products there will be in the array.
What would be a clean way to loop though all the products?
I don't want to use a foreach loop since it will also go through all the other items in the (large) array.
I cannot use a for loop cause I don't know (yet) how many products the array contains.
I can do a while loop:
$i = 0;
while(true) { // doing this feels wrong, although it WILL end at some time (if there are no other products)
if (!array_key_exists('product_name_'.$i, $data)) {
break;
}
// do stuff with the current product
$i++;
}
Is there a cleaner way of doing the above?
Doing a while(true) looks stupid to me or is there nothing wrong with this approach.
Or perhaps there is another approach?
Your method works, as long as the numeric portions are guaranteed to be sequential. If there's gaps, it'll miss anything that comes after the first gap.
You could use something like:
$names = preg_grep('/^product_name_\d+$/', array_keys($data));
which'll return all of the 'name' keys from your array. You'd extract the digit portion from the key name, and then can use that to refer to the 'desc' section as well.
foreach($names as $name_field) {
$id = substr($names, 12);
$name_val = $data["product_name_{$id}"];
$desc_val = $data["product_desc_{$id}"];
}
How about this
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// loop body
$i++;
}
I think you're close. Just put the test in the while condition.
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// do stuff with the current product
$i++;
}
You might also consider:
$i = 0;
while(isset($data['product_name_'.$i])) {
// do stuff with the current product
$i++;
}
isset is slightly faster than array_key_exists but does behave a little different, so may or may not work for you:
What's quicker and better to determine if an array key exists in PHP?
Difference between isset and array_key_exists

Categories