I have an array ($myArray) like this:
print_r(array_values ($myArray));
result: Array (
[0] =>
[1] => Array (
[id] => 1
[name] => ABC
)
[2] => Array (
[id] => 2
[name] => DEF
)
)
I'm trying to get each ID and NAME.. So Im trying this:
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
I'm facing two problems:
I get a PHP WARNING that says: " Invalid argument supplied for foreach() on line 29
This line is: foreach($value as $result) {
I would like to get keys to ID and NAME to place them in correct places. This ways echo "1ABC" and "2DEF"
Any idea? Thanks for helping.
Basically, the error triggered, since the array in your example (index zero in particular) is not an array (most likely an empty string/null ) which is being used inside foreach.
Since one of the elements is not an array, you could just check that if its an array or not using is_array():
foreach($myArray as $values) {
if(is_array($values)) {
echo $values['id'] . ' ' . $values['name'] . '<br/>';
}
}
Alternatively, you could also use array_filter() in this case which in turn removes that empty index zero, so that you could just use that loop that you have. You wouldn't have to check for that empty element.
$myArray = array_filter($myArray);
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
try this,
foreach (array_slice($myArray ,1) as $value) {
foreach($value as $result) {
echo $result;
}
}
the 1st position is empty so omit first position
Related
I decoded a JSON array which contained keys and values in PHP. The JSON looks like this (shortened for easier understanding):
[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]
After I json_decode'd it, it looked like this:
Array ( [0] => stdClass Object ( [code] => 123 ) [1] => stdClass Object ( [identification] => Some item ) [2] => stdClass Object ( [price] => $20 ) )
How can I read both the key and the value?
I already tried searching on SO all over and already tried something like this:
foreach ($jarray as $key) {
echo 0->$key;
}
which throws an 500 (ISE) error.
Also tried this:
foreach ($jarray as $key => $value) {
echo $key;
echo $value;
}
which also throws an 500 error.
I don't know how to accomplish this...
EDIT: Basically, I just want to iterate trough the whole thing and get key and value every time, like this:
code - 123
identification - Some item
price - $20
...
$json = '[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]';
$jarray = json_decode($json, true);
foreach ($jarray as $value) {
foreach ($value as $key => $val) {
echo $key;
echo $val;
}
}
I hope so it will reduce loop process confusion and simple to do this task.
$text = '[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]';
$array = json_decode($text);**strong text**
foreach($array as $value)
{
$array = (array)$value;
$x = each($array);
echo $x['key'];
echo "====>>>>";
echo $x['value'];
echo "<br/>";
}
I have an array, the output of print_r is:
Array ( [0] => Array ( [ID] => 1 [col1] => 1 ) [1] => Array ( [ID] => 2 [col1] => 2 ) )
Could you help of kind of array it is? So that I could research more about it? What I want is to get ID and col1 values
I've tried to use foreach:
foreach($array_name as $key=>$value){
print "$key holds $value\n";
}
The output I get is 0 holds Array 1 holds Array
And I would simply like to get:
1 1
2 2
It's a multi dimensional array, or an array where each element is another array. So you'll need to loop twice. Try this to look at it:
foreach($array_names as $arr)
{
foreach($arr as $key => $val)
{
print "$key = $val\n";
}
}
Or, to get your just added desired output, do this:
foreach($array_names as $arr)
{
foreach($arr as $key => $val)
{
print "$val ";
}
print "\n";
}
Or this:
foreach($array_names as $arr)
{
print $arr['ID'] . " " . $arr['col1'] . "\n";
}
or a few other ways but you should be getting the picture.
I have an array of arrays that looks like this:
Array
(
[0] => Array
(
[id] => 39
[nume] => Ardeleanu
[prenume] => Bogdan
[crm] => Array
(
)
)
[1] => Array
(
[id] => 40
[nume] => Avram
[prenume] => Corina
[crm] => Array
(
[2014-02-27] => 2
[2014-02-28] => 1
)
)
)
Here is my code :
foreach ($newOrders as $crm) {
foreach ($crm as $angajati) {
foreach ($angajati['crm'] as $val) {
echo $val;
}
}
}
I getting the Warning:
Illegal string offset 'crm'.
What am I missing ?
Does it helps ?
foreach ($newOrders as $key=>$val) {
if(array_key_exists("crm",$val) && count($val["crm"]) > 0 ){
foreach($val["crm"] as $k=>$v){
echo $k." = ".$v."<br />";
}
}
}
When we loop through a multi dimentional array its better to check if the keys are available if the corresponding values are again array and also to check if the array of values have some elements before doing loop.
So here first checking if "crm" is available and if the value i.e. again an array having some elements before doing a loop and its done by the line
if(array_key_exists("crm",$val) && count($val["crm"]) > 0 ){
This is done to avoid further notice like invalid index and invalid argument supplied in foreach if the element is missing or the data array is not present.
You're trying to loop over whole 2-nd level array, but only crm key points to array. Thus, you need to do:
foreach ($newOrders as $crm)
{
if(isset($crm['crm']))
{
foreach ($crm['crm'] as $val)
{
echo $val;
}
}
}
-if you want to get values in crm key. It may not exist, thus, I've added isset check.
Not sure why I can't this to work. My json is:
[values] => Array
(
[0] => Array
(
[field] => id1
[value] => 985
)
[1] => Array
(
[field] => id2
[value] => 6395
)
[2] => Array
(
[field] => memo
[value] => abcde
)
I simply want the values of id2
I tried:
foreach ($json['values'] as $values) {
foreach ($json as $key=>$data) {
if ($data['field'] == 'id2') {
$result = $data['value'];
print '<br>value: '.$result;
}
}
}
Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.
there's no need for inner loop, after the first one $values already contain the exact array that you are looking for
foreach ($json['values'] as $values) // $values contain
{
if ($values['field'] == 'id2')
{
$result = $values['value'];
print '<br>value: '.$result;
}
}
foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
foreach ($values as $key=>$data) { //you're looping inside values taking the array index $key and the value inside that index $data
if ($key == 'id2') { //test if $key (index) is = to id2
print '<br>value: '.$value; // print the value inside that index
}
}
}
this is just an explanation, to what is going wrong with your code, but as #Pawel_W there is no need for the second foreach loop you can directly test
if($values['field']=='id2'){ print $values['value'];}
I think you just need to use array_search.
And here is recursive array_search ;
Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:
array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));
If your field names are always unique and you just want a single scalar:
array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });
(note that this one is not ideal since it will walk all the array even if match is found in first element)
And here's a gist with both in this and function form + output.
I have an array of objects; running print_r() returns the output below;
Array
(
[0] => stdClass Object
(
[sm_id] => 1
[c_id] => 1
)
[1] => stdClass Object
(
[sm_id] => 1
[c_id] => 2
)
)
How to loop through the result and access the student class objects?
Use
//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
echo $value->sm_id;
}
OR
//$arr should be array as you mentioned as below
foreach($arr as $value){
echo $value->sm_id;
}
Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:
foreach ($arr as $item) {
echo $item->sm_id;
}
In this example each of our values in the $arr will be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:
foreach ($arr as $index => $item) {
echo "Item at index {$index} has sm_id value {$item->sm_id}";
}
Assuming your sm_id and c_id properties are public, you can access them by using a foreach on the array:
$array = array(/* objects in an array here */);
foreach ($array as $obj) {
echo $obj->sm_id . '<br />' . $obj->c_id . '<br />';
}
Recursive traverse object or array with array or objects elements:
function traverse(&$objOrArray)
{
foreach ($objOrArray as $key => &$value)
{
if (is_array($value) || is_object($value))
{
traverse($value);
}
else
{
// DO SOMETHING
}
}
}