0

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?

uneeb meer
  • 882
  • 1
  • 8
  • 21

3 Answers3

1

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'
)
Florian Müller
  • 7,448
  • 25
  • 78
  • 120
  • my bad echoing an array but var_dump still returns an array whereas i need id,name and path values only – uneeb meer May 17 '17 at 14:29
  • @uneebmeer If you are sure the structure of the Array will stay like this, you can use my edited code answer to get an Array where the key is the name and the value is the file (see my edited answer). – Florian Müller May 17 '17 at 14:32
1

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.

Echoes
  • 324
  • 4
  • 14
  • just one more thing for conceptual purpose, can you explain to me how you made that array logically like the index 0 inside the array how are they working i want to research more on advanced arrays bu i just need an initial concept – uneeb meer May 17 '17 at 14:43
0

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.

zenwraight
  • 2,002
  • 1
  • 10
  • 14