How to use a foreach loop with a multidimensional array? - php

I have a multidimensional array and I was given a foreach loop, but don't know how to echo out all the values without using print_r. I do get a result if I echo $array[0][0]; outside the foreach loop, for the first result.
I had seen other examples but nothing to show the results other than print_r and they tend to do only a single array, not a multidimensional array.
I had seen this foreach loop that seems like it would work, but I only get errors if I try to do echo $new_array inside the foreach loop. How can I use this for something like this situation?
foreach($array as $key=>$val) {
$new_array[] = $val['key'];
}
array results from print_r
[0] => Array
(
[0] => 2
[audit_inspectionID] => 10
[1] => 2015-08-12
[created] => 2015-08-12
[2] => 2016-08-11 16:26:22
[modified] => 2016-08-11 16:26:22
[class_answer] => Array
(
[0] => Needs Improvement
[1] => Need To Correct
[2] => Needs Immediate Action
)
)
[1] => Array
(
[0] => 12
[audit_inspectionID] => 12
[1] => 2016-08-12
[created] => 2016-08-12
[2] => 2016-08-11 16:26:22
[modified] => 2016-08-11 16:26:22
[class_answer] => Array
(
[0] => Needs Improvement
[1] => Need To Correct
[2] => Needs Immediate Action
)
)

I'm not really sure what you're asking, but if you want something which will print out all of the keys and values (In what format? You don't specify) regardless of arrays nested inside each other you could do something like:
function arrayToString(array $array)
{
$out = "";
foreach ($array as $key => $value) {
if (is_array($value)) {
$out .= "$key => (" . arrayToString($value) . "), ";
} else {
$out .= "$key => $value, ";
}
}
return $out;
}
The you can echo arrayToString($myArray) where $myArray is the array you want to echo - it'll leave trailing commas but I'm sure you can modify it to do what you need it to, this should give you an idea of how to go about it.
Is that the sort of thing you wanted? I don't really see the point of this but hopefully this helps you out.

Related

PHP Array rearrange numeric key as parrent key

i want to rearrange a simple multidimensional array.
Array
(
[pieces] => Array
(
[0] => 2
[1] => 9
)
[start] => Array
(
[0] => 0001
[1] => 9901
)
[end] => Array
(
[0] => 0002
[1] => 9909
)
[group] => Array
(
[0] => 0001-0100
[1] => 9901-9999
)
)
to
Array
(
[tokens] => Array
(
[0] => Array
(
[start] => 0001
[end] => 0002
[pieces] => 2
[group] => 0100
)
[1] => Array
(
[start] => 9901
[end] => 9909
[pieces] => 9
[group] => 9901-9999
)
)
)
I have tried something similar this:
$keys = array_keys($array);
foreach ($keys as $key => $val) {
foreach ($array as $k => $v){
foreach($array[$v] as $tk => $tv){
if($val == $k){
$new['tokens'][][$val] = $tv;
}
}
}
}
The numeric is the set of tokens which i prosted from my form,
Please can anyone explain me what i do wrong?
I am working some hours with different codes (i know the solution is very simple) but I am a little bit confused :/
Thank you very much!
BR KK
The Fourth Bird's solution is quite rigid in that it:
Requires an explicitly-defined key in the loop condition.
Enforces that the entire result has no more items than that one key has.
Assumes and enforces that the input keys are sequential and zero-indexed.
The below will work no matter what:
foreach( $array as $y => $inner ) {
foreach( $inner as $x => $value ) {
$new['tokens'][$x][$y] = $value;
}
}
Demo: https://3v4l.org/Rmdtd
Edit: I think it's worth preserving The Fourth Bird's explanation of the trouble with the posted code from his now-deleted answer:
You are trying to index into $array[$v], but $v in the case is one
of the sub arrays. According to the array
docs:
Arrays and objects can not be used as keys. Doing so will result in
a warning: Illegal offset type.
Make sure that you have error_reporting turned up to E_ALL while you're developing code so that you can see non-critical messages that indicate current and/or future problems.

Explode foreach to new array

I have JSON API response which look something like this
Array
(
[sections] => Array
(
[0] => Array
(
[id] => 115000089967
[url] => xxxxx
[html_url] => ArticleHTML1
[category_id] => 204458828
[position] => 0
[sorting] => manual
[created_at] => 2016-12-19T14:56:23Z
[updated_at] => 2017-02-03T08:23:04Z
[name] => ArticleName1
[description] =>
[outdated] =>
)
[1] => Array
(
[id] => 207077828
[url] => xxxxxx
[html_url] => ArticleHTML2
[category_id] => 204458828
[position] => 1
[sorting] => manual
[created_at] => 2016-11-14T09:28:30Z
[updated_at] => 2017-02-02T09:15:42Z
[name] => ArticleName2
[description] =>
[outdated] =>
)
)
[page] => 1
[per_page] => 30
[page_count] => 1
[sort_by] => position
[sort_order] => asc
)
I have successfully iterated this with foreach, so return looks like this:
ArticleName1 ArticleHTML1
ArticleName2 ArticleHTML2
So I took [name] and [html_url] from each like this:
$details1 = array('name');
$details2 = array('html_url');
foreach($sections['sections'] as $article) {
foreach($details1 as $detail) {
echo "$article[$detail] ";
}
foreach($details2 as $detail) {
echo "$article[$detail]\n";
}
}
But what I want next is that, that response should be exploded to one single array like this:
Array
(
[0] => ArticleName1 ArticleHTML1
[1] => ArticleName2 ArticleHTML2
)
I already managed to explode those to individual arrays:
foreach($sections['sections'] as $article) {
foreach($details1 as $detail) {
$name = "$article[$detail] ";
}
foreach($details2 as $detail) {
$url = "$article[$detail]\n";
}
$string = $name . $url;
$array = explode(' ', $string, 1);
print_r($array);
}
but I need just one array.
How? I'm lost or just doesn't understand, am I even close?
EDIT
The thing here is that the JSON dump is pretty large and I only need few things (name and url). So I was thinking that I first grab the whole thing, then I just take the names and urls (like the first foreach is doing), and then put those back to array. Because from those names and urls I need only last 12 keys, and taking those from sinlge array would be easy.
Tho it would be perfect, if I could sort out the keys which I don't want, in the first place. That would solve my problem. Then I wouldn't need a new array etc.
You're making this much more difficult than it needs to be. It's just a single loop:
$array = array();
foreach ($sections['sections'] as $article) {
$array[] = $article['name'] . ' ' . $article['html_url'];
}

Syntax for reading an array in php

I have an array, stored in $array, that with
print "<pre>";
print_r($array);
print "</pre>";
gives an output like this:
Array
(
[device] => Array
(
[0] => Array
(
[#attributes] => Array
(
[name] => Low volt light
[id] => 10
[type] => Z-Wave Switch Multilevel
[value] => 0
[address] => 00016922-018
[code] =>
[canDim] => True
[lastChange] => 26-07-2014 17:31:33
[firstLocation] => Kitchen
[secondLocation] => Main
)
)
[1] => Array
(
[#attributes] => Array
(
[name] => Light
[id] => 11
[type] => Z-Wave Switch Multilevel
[value] => 99
[address] => 00016922-019
[code] =>
[canDim] => True
[lastChange] => 31-07-2014 20:01:05
[firstLocation] => Bedroom
[secondLocation] => Main
)
)
I cannot find my way to access/display for example the value (in this case 0) of device with [id]=>10. What syntax would be the right one in php?
There's not an easy way to do this, without looping through the array.
e.g.
foreach ($array['devices'] as $device) {
if ($device['#attributes']['id'] === $idBeingSearchedFor) {
// Do something with $device.
}
}
Due to the #attributes array key, I'm guessing that this came from XML at some point: You might consider using Simple XML to parse it instead, as you could potentially use XPath then, which does support this type of access.
Alternatively again, you could reformat the array so it could be easily accessed by ID.
For example:
$formattedArray = array();
foreach ($array['devices'] as $device) {
$id = $device['#attributes']['id'];
$formattedArray[$id] = $device;
}
You could then access the device by its ID as follows:
$device = $formattedArray[$idBeingSearchedFor];
You could do it like that:
$id = 10;
$device = array();
foreach($array['device'] as $devices) {
if($devices['#attributes']['id'] == $id) {
$device = $devices['#attributes'];
break;
}
}
echo $device['value'];
Looks like SimpleXML, and if that is the case then those arrays are actually objects that, when put through print_r, look just like arrays. To access them, do the following:
Get straight to the data:
$name = $array->device[0]->attributes()->name;
Or loop through each of the attributes in the first device:
foreach ($array->device[0]->attributes() as $key => $value) {
// Do something with the data. $key is the name of the
// attribute, and then you have the $value.
}
Or you could loop through all the devices:
foreach ($array->device as $device) {
foreach ($device->attributes() as $key => $value) {
// Do something
}
}
It's simple ... try below...
print $array['device'][0]['#attributes']['id'];
or
print $array['device']['0']['#attributes']['id'];

Looping through an Array in Php

Can't seem to figure this out. I struggle so badly with arrays. I am trying to get the data out of this array and keep getting errors.
I tried using this code below and several other attempts and failed miserably. What's the best way to remember how to do this? Everytime I don't code Php for a couple months I seem to forget everything...
foreach( $data as $key) {
foreach( $key as $value => $sum) {
echo $sum;
}
}
Array
(
[result] => OK
[data] => Array
(
[destination] =>
[tracking] => Array
(
[0] => Array
(
[loc] => Array
(
[city] =>
[territory] => ME
[country] => US
)
[desc] => Delivered
[stamp] => 1384977300
[time] => 11/20/13 11:55 am
[locStr] => ME, US
[geo] => Array
(
[lat] => 45.253783
[lon] => -69.4454689
)
)
iterate through tracking?
if ($arr['result'] == "OK") {
for ($i=0; $i < count( $arr['data']['tracking'] ); $i++) {
// do stuff with $arr['data']['tracking'][$i]
}
}
In php there are basically two different type of arrays. key/value based array and element based array.
An element based array is
$arr = array("a", "b", "c");
echo $arr[0]; // prints a
echo $arr[2]; // prints c
// hash - k/v array
$arr = array("monkey" => "banana", "chicken" => "egg");
echo $arr["monkey"]; // prints banana
// combination
$arr = array( array("monkey" => array("banana", "water")));
echo $arr[0]["monkey"][1]; // prints water
hope this helps.
I think your code is not wrong. you have three dimensional array. you have only two foreach. you have to loop within a loop within a loop. and if you try to echo an array Ofcourse you will have an error so you should check first if that output is an array or not.

Pulling out array elements

So I am print_r-ing an array, generated as follows:
while ($twitgroup = mysql_fetch_array($resulttwitter)) {
print_r($twitgroup);
}
I get this output (with multiple more arrays, dependent on rows).
Array ( [0] => composed [category] => composed [1] => 330 [value] => 330 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => elated [category] => elated [1] => 2034 [value] => 2034 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => unsure [category] => unsure [1] => 2868 [value] => 2868 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => clearheaded [category] => clearheaded [1] => 1008 [value] => 1008 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => tired [category] => tired [1] => 2022 [value] => 2022 [2] => 1344384476.94 [timestamp] => 1344384476.94 )
I want to be able to pull individual values here, but I'm having trouble. I'm trying to use a while loop on these arrays, but I think maybe that's wrong. Should I perhaps use a foreach loop, and then on the output of that foreach, access each element of the array?
Say for example, I want to grab composed, and the value of composed. How would I do that?
I'm pretty good with arrays/lists in Python, but my experience with arrays in PHP is somewhat lacking.
Use
while ($row = mysql_fetch_assoc($resulttwitter)) {
$twitgroup[$row['category']] = $row;
}
echo $twitgroup['composed']['value']; // outputs 330
echo $twitgroup['composed']['timestamp']; // outputs 1344384476.94
If you only want categories and their values use
while ($row = mysql_fetch_assoc($resulttwitter)) {
$twitgroup[$row['category']] = $row['value'];
}
echo $twitgroup['composed']; // outputs 330
Replace mysql_fetch_array with mysql_fetch_assoc to eliminate duplicates. Then this:
while ($twitgroup = mysql_fetch_assoc($resulttwitter))
{
foreach ($twitgroup as $key => $value)
{
echo "$key => $value\n";
}
}
You could also get the elements by name:
while ($twitgroup = mysql_fetch_assoc($resulttwitter))
{
echo "category => " . $twitgroup["category"] . "\n";
echo "value => " . $twitgroup["value"] . "\n";
echo "timestamp => " . $twitgroup["timestamp"] . "\n";
}
mysql_fetch_array includes each field twice in the result, one associated with a numeric key and one with the field name.
That is why you have
[0] => composed
[category] => composed
[1] => 330
[value] => 330
You can access field either like :
$twitgroup[0]
or like :
$twitgroup['category']
So, you can access your each row like :
while ($twitgroup = mysql_fetch_array($resulttwitter)) {
print $twitgroup['category']; // or print $twitgroup['0'];
print $twitgroup['value']; // // or print $twitgroup['1'];
// or by the corresponding numeric indices.
}
If at all you want to limit your result to either numeric or Associative array, add an additional flag (result_type) to your mysql_fetch_array :
mysql_fetch_array ($resulttwitter, MYSQL_ASSOC) // or mysql_fetch_array ($resulttwitter, MYSQL_NUM)
Having said all this, it is highly discouraged using mysql_* functions in PHP since they are deprecated. You should use either mysqli or PDO instead.
This is what you have:
Array (
[0] => composed
[category] => composed
[1] => 330
[value] => 330
[2] => 1344384476.94
[timestamp] => 1344384476.94
) Array (
[] =>
[] =>
...
) ...
Arrays in PHP are called associative arrays because they can have
either keys out of integers, strings or anything else.
You have an array with arrays in it.
To access the individual fields, it would be most convenient to use a
for each loop.
$record=0;
foreach ($array as $k => $subArray) {
$record++;
foreach($subArray as $field => $value) {
printf("%d: %s = %s\n", $record, $field, $value);
}
}
Its seems to me that there is something wrong with the way you are fetching
the data, becasue half the fields seem redundant. You can use the string keys
to figure out the contents. so there is no need for the n => name entries.
If that can't be helped, I guess you could iterate over the values with
$ix=0;
for ($i=0; $i < (count($array)/2); $i++){
printf("%s\n", $array[$ix]);
$ix++;
}

Categories