How can I use foreach to process a multidimensional php array? - php

I parsed a JSON file with json_decode, and the result is a long multidimensional array like the following:
Array
(
[Basic] => Array
(
[0] => Array
(
[text] => Taunt.
[playerClass] => Shaman
[locale] => enUS
[mechanics] => Array
(
[0] => Array
(
[name] => Taunt
)
)
)
)
[Classic] => Array
(
[0] => Array
(
[cardId] => CS2_188o
[name] => 'Inspired'
[mechanics] => Array
(
[0] => Array
(
[name] => OneTurnEffect
)
)
)
)
)
I want to use a foreach to insert the data into a datatable but I can't make it work with this multidimensional array. How would I do that?

You must use recursive array to do it like this
function build($fullArray)
{
foreach ($fullArray as $item) {
if (is_array($item)){
build($item);
}
else{
echo $item["cardId"];
echo $item["name"];
....
}
}
}

Use this:
foreach ($items as $item) {
if (is_array($item)){
foreach ($item as $it) {
echo $it["name"];
}
}
echo $item["cardId"];
echo $item["name"];
....
}

Related

PHP Loop through array with no index names

In PHP I have this structure of Array (some are empty, some not, some are multiple items):
Array
(
[0] => Array
(
)
[1] => Array
(
[0] => 16534
)
[2] => Array
(
)
[3] => Array
(
[0] => 16532
[1] => 16533
)
[4] => Array
(
)
[5] => Array
(
[0] => 14869
)
}
I want to loop through this array, so as the result I get only the numbers (all of them).
I tried it this way:
foreach ($myarray as $item) {
echo '<pre>' . print_r($item) . '</pre>';
// $result[] = $this->myMethod($item);
}
So in foreach I want to use all the items from array in my method.
However when I echo the $item in the loop, I have something like this:
Array ( )
Array ( [0] => 16534 )
Array ( )
Array ( [0] => 16532 [1] => 16533 )
Array ( )
Array ( [0] => 14869 )
So still arrays (also the empty ones), and not numbers.
Can you please help with this?
UPDATE: I just noticed, some of the arrays looks like this:
[6] => Array
(
[0] => Array
(
[id] => 269
[hours] => 21.0
)
)
[7] => Array
(
[0] => Array
(
[0] => Array
(
[id] => 2
[hours] => 12.0
)
[1] => Array
(
[id] => 7
[hours] => 24.0
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[hours] => 5.0
)
[1] => Array
(
[id] => 7
[hours] => 0.583
)
)
)
but here the solution works not.
This one seems working but it is now brutal foreach in foreach solution:
foreach ($myarray as $item2) {
foreach ($item2 as $key2 => $val2) {
if (isset($val2)) {
foreach ($val2 as $key4 => $val4) {
echo $val4['id'].',';
}
}
}
}
Just merge the array which will also remove the empties:
foreach(array_merge(...$myarray) as $item) {
// echo '<pre>' . print_r($item) . '</pre>';
$result[] = $this->myMethod($item);
}
This will also work and may be faster:
$result = array_map([$this, 'myMethod'], array_merge(...$myarray));
If you have an old PHP version you'll have to use array() instead of [] and:
call_user_func_array('array_merge', $myarray)
You are only looping through the main array.That's the reason why you are getting an array when you are printing the result set.(because those values are stored in sub arrays and you are not looping them.)
And to remove the sub arrays with empty values I'll use isset() so that you will get only the values.
Change your code into this.
foreach ($myarray as $item) {
foreach($item as $key=>$val){
if(isset($val){
$values[] = $val;
// $result[] = $this->myMethod($values);
}
}
}

Convert Complex array to simple one (for CSV)

I want to convert my complex array to simpler one for exporting that converted simpler array to the CSV file.
Currently my array structure is like:
Array
(
[0] => Array
(
[_source] => Array
(
[block] => Array
(
[0] => Kurud
)
[district] => Array
(
[0] => Dhamtari
)
[state] => Array
(
[0] => Chhattisgarh
)
)
)
[1] => Array
(
[_source] => Array
(
[block] => Array
(
[0] => North-Bangeluru
)
[district] => Array
(
[0] => Bangalore
)
[state] => Array
(
[0] => Karnataka
)
)
)
)
and I want to convert above array to the below given format:
array(
array("block", "district", "state"),
array("Kurud","Dhamtari","Chhattisgarh"),
array("North-Bangeluru","Bangalore","Karnataka")
)
So keys will be the first element and then each element with his data.
This is what I tried:
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result);
}
else {
$result[$key] = $value;
}
}
print_r(result);
thanks in advance...
How about:
$keys = array_keys($arr[0]["_source"]);
$res[] = $keys;
foreach($arr as $e) {
$temp = [];
foreach($keys as $k)
$temp[] = $e["_source"][$k][0];
$res[] = $temp;
}
Reference: array-keys
Live example: 3v4l

array to string conversion error on view ci

i have an array which is in the following format
Array ( [0] => Array ( [id] => 13 [path] => Array ( [0] => Array ( [name] => Pistachios [path] => E_906.JPG ) ) ) [1] => Array ( [id] => 14 [path] => Array ( [0] => Array ( [name] => Almonds [path] => almond.jpg ) ) ) )
now what i need is i need the id ,name and path values from this array it basically has two indexes 0 and 1 i am using foreach loop for this purpose
here's my code
<?php
foreach ($child3 as $key => $value){
echo $key;
}
?>
when is echoing out the key it prints correct 0,1 but when i try to echo the value like
<?php
foreach ($child3 as $key => $value){
echo $value;
}
?>
it is giving me an error of Array to string conversion any recommendations?
Try this:
foreach ($child3 as $key => $value){
$id = $value['id'];
$name = $value['path'][0]['name'];
$path = $value['path'][0]['path'];
}
**this is assuming that your [path] always contains just one array element.
In your second foreach loop, $value is the Array with key path. echo() expects a string as parameter, but because $value is an Array, PHP tries to convert it to a string and fails.
Try var_dump() instead:
<?php
foreach ($child3 as $key => $value){
var_dump($value);
}
?>
Your Structure is this:
Array (
[0] => Array ( <<- you tried to echo this array
[id] => 13
[path] => Array (
[0] => Array (
[name] => Pistachios
[path] => E_906.JPG
)
)
)
[1] => Array (
[id] => 14
[path] => Array (
[0] => Array (
[name] => Almonds
[path] => almond.jpg
)
)
)
)
If you know this structure is fixed, try this:
$files = array();
foreach ($child3 as $child) {
$files[$child['path'][0]['name']] = $child['path'][0]['path'];
}
So var_dump($files) would give you this:
Array (
'Pistachios' => 'E_906.JPG'
'Almonds' => 'almond.jpg'
)
Try using
<?php
foreach ($child3 as $key => $value){
print_r($value);
}
?>
Because you have $value as an array, that's why you are getting that error.

PHP Array to Variables after Foreach loop

Hi My Code is the following
if(is_a($values, 'pingidentity\opentoken\helpers\multistringarray'))
{
foreach($values->keySet() as $key)
{
foreach($values->get($key) as $value)
{
$i++;
print "<tr><td class=\"d".($i&1)."\">".$value."</td><tr>";
}
}
}
When I print_r the array output is
pingidentity\opentoken\helpers\MultiStringArray Object
(
[_values:pingidentity\opentoken\helpers\MultiStringArray:private] => Array
(
[not-before] => Array
(
[0] => 2014-06-13T19:33:15Z
)
[authnContext] => Array
(
[0] => urn:oasis
)
[email] => Array
(
[0] => test#test.com
)
[subject] => Array
(
[0] => usernametest
)
)
)
I'm looking for help on how to take the output of the array and input the values into variables
I've now did the followng to cast the object to array
$array = (array) $values;
with results as following
Array
(
[not-before] => Array
(
[0] => 2014-06-13T23:17:08Z
)
[authnContext] => Array
(
[0] => urn:oasis )
[email] => Array
(
[0] => test#test.com
)
[subject] => Array
(
[0] => usernametest
)
)
)
remember that you can access to the value of the key:
$result = array();
foreach($values as $key => $value){
if($key != 'excludeVal' && $key != 'exclude2') //here you can exclude some keys that you don't need
$result[$key] = $value;
}
after that you can use extract function
extract($result);
or even use extract($values);
this function return each key like a variable, eg: if you has a key named ["key1"] after the extract call you can use the variable $key1 and it has the value of the key
You can type cast this object to array.
OR use Object and use -> operator to access the content

How to echo objects as string which is stored in an array?

I want to echo cer_type from this array
Array
(
[0] => stdClass Object
(
[id] => 1
[cer_type] => S.L.C.
)
[1] => stdClass Object
(
[id] => 3
[cer_type] => Intermediate
)
)
Try this:
<?php
echo $array[0]->cer_type;
// or if you want to loop through the array:
foreach ($array as $element) {
echo $element->cer_type;
}

Categories