Reputation: 61
I have a multi-part array that I want to grab a piece of and create a variable for it. Below is a sample of the array:
array(17) {
[0]=> array(2) {
[0]=> int(1325003844) [1]=> array(2) {
[0]=> int(31) [1]=> string(19) "ONBOARD TEMPERATURE" }
}
There are 32 different parts like this where the value I want (like the text in quotes above) can be found at $foo[x][1] with x being a value from 0-31. So I am wondering if I can use foreach or for to create a loop that will go through each iteration of the variable and pull that text and add it to a variable.
So the current code I have is:
if(isset($result[1][10])) { // If index 10 of $result exists
$json_a = $result[1][10];
var_dump ($json_a);
To get the value I want in a single variable, I need to assing $foo_01 to $json_a[0][1] right now, and then do that 32 times. ($json_a[1][1], $json_a[2][1], $json_a[3][1], etc.) I would rather just have one statement taht assigns them all at once.
Let me know if you need additional information. Thanks again!
Upvotes: 2
Views: 966
Reputation: 29170
Of course you can.
//Initialize an array variable to hold the names
$names= array();
//Creates an array of 32 strings (the names)
foreach ($items as $item){
$names[]=$item[1];
}
//If you want to display all of the name at once, you can easily
//Implode the array to echo all of the items with a linebreak in between
echo implode('<br />', $names);
//or you can cycle through the results and do something for each name
//although this can be done in the original loop.
foreach ($names as $name){
echo $name.'<br />';
}
On a side note, the array architecture you show seems a little weird to me. Knowing not much at all about what you're trying to do, do you think a format like this would be better?
array(31) {
[0]=> array(2) {
[id]=> int(1325003844),
[name]=> "ONBOARD TEMPERATURE"
},
[1]=> array(2) {
[id]=> int(1325003845),
[name]=> "NAME 2"
},
etc...
}
This way you already have your finished array, ready to loop through?
UPDATE
foreach($results as $result){
if(isset($result[1][10])) { // If index 10 of $result exists
$foo[] = $result[1][10];
}
}
//Then you can access each one when needed
echo $foo[1];
Upvotes: 3
Reputation: 2575
If you use two consecutive '$', PHP will actually use the value of a variable to create a new variable of that name. Example:
$var1 = 'variable2'
$$var1 = 'hello';
echo $var1;
echo $variable2;
Will output:
variable2
hello
From your above examples, though, your naming conventions dont seem to support that (there's a space in "ONBOARD TEMPERATURE") so, you might be better using an array with associative id keys. Example:
$values[$foo[x][1]] = $foo[x][0];
Would get you a variable of $values['ONBOARD TEMPERATURE']
that would output 31
.
Upvotes: 0