php, how to grab data from an multidimensional array? - php

i have an array that looks like this:
foreach($obj as $key => $value)
{
print_r ($obj);
}
Array
(
[id] => 24991526504444
[name] => 21test
[picture] => http://profile.ak.fbcdn.net/hprofile-ak-sn4/276505_2499152255_s.jpg
[link] => http://apps.facebook.com/test/vote=6189373
[likes] => 1
[category] => Website
[parking] => Array
(
[street] => 0
[lot] => 0
[valet] => 0
)
[payment_options] => Array
(
[cash_only] => 0
[visa] => 0
[amex] => 0
[mastercard] => 0
[discover] => 0
)
)
how can i get the data from this array, for ex the id, or the likes.
i've tryed echo $key['likes'] or echo $key[$value['likes']] and some more combinations and it doesn't work
any ideas?
thanks

$key isn't your array, $obj is your array. You should be using $obj['likes'] or $obj['parking']['street']. You don't have to enumerate the keys to access the keys/values within the object, just use $obj.
Also, your foreach doesn't make sense:
foreach($obj as $key => $value)
{
print_r ($obj);
}
This reads "For each key in the array, print the entire array". You don't have to loop at all, the whole purpose of print_r is to recursively print the contents of an array for you with no looping. Just use
print_r($obj);

Please read the manual on arrays.
You don't need a loop to access an array. What you want can be done simply with $obj['id'] or $obj['likes'].

According to this:
foreach($obj as $key => $value)
{
print_r ($obj);
}
the array you have displayed is actually the full structure of $obj and not any of its key=>value pairs.
So you should just need:
echo $obj['likes'];
echo $obj['id'];

You are using foreach, that means you are iterating array elements, you should be using
$obj['likes']
should return the value on the array (1 in your case).
And for the multidimensional ones
$obj['payment_options']['cash_only']
should return the value (0 in your case)

Related

PHP, getting $value out of a specific $key in associative multidimensional array

I'm quite new with PHP and I'm facing a problem with arrays.
say I have a multidimensional associative array called $charsarray like this:
[1] => ([name] => mickey [surname] => mouse)
[2] => ([name] => donald [surname] => duck)
...
[N] => (...)
I need to extract the "surname" field of each entry so my code has nested foreach:
foreach($charsarray as $key => $value )
{
foreach($value => $singlechar)
{
echo $singlechar
}
}
This outputs both mickey mouse donald duck since these are the values of the associative array.
If I want to extract only surnames I could write an if statement to check against the key surname.
Is there a better approach to this without using the if statement ?
You don't need to loop through the entire thing. You can just reference the specific value in the array by using correct index (surname).
foreach($charsarray as $key => $value )
{
echo $value['surname']
}
Surname also a key in that array so you need to print like as below
foreach($charsarray as $key => $val){
echo $val['surname'];
}

get the value from the associtive array in table

Array
(
[0] => Array
(
[datas] => Array
(
[res] => 1
[rows] => Array
(
[0] => stdClass Object
(
[a] => 11
[b] => 901
[c] => 2
[d] => 2
[e] => A
[f] => BT
[g] => arushi
[h] => arushi#gmail.com
[i] => 123445
[j] => 12355.jpg
)
)
)
)
[1] => Array
(
[datas] => Array
(
[res] => 1
[rows] => stdClass Object
(
[person_name] => arushi
)
)
)
)
if i get the value in that kind off array how can i get the value of
both partially with different variable m not able to understand the
structure of the array..
need to get the value in table seperatly in different different table with same page how i can get the values
You would need to do a foreach loop. The only problem is that if you want to make it dynamic and grab the data by itself without you telling it what to get. If not it means you would have to know exactly what you need and the structure of your results. But seeing that there is a pattern you can do some checks until you reach rows. For example ($array would be the variable that has the data you provided):
foreach ($array AS $arr) {
// To make you function/check work faster,
// before even entering to fetch for data
// you can check if it has any data, else you
// probably will end up with an error
if (isset ($arr ['datas']) && $arr ['datas']) {
foreach ($arr ['datas'] AS $data) {
if (isset ($arr ['res']) && 0 < $arr ['res']) {
// here is where it gets tricky because
// from you example its either an array or an object
// but the kool part about it is that you can convert an object into an array
// or just leave it as is because the foreach will take care of it either way :)
// first check it it is an object and convert if yes
$row = $arr ['rows'];
if (!is_array ($row))
$row = (array)$row; // converting it to array is super easy :)
foreach ($row AS $key=>$dat) {
// from here your result can either be another array or just data
// so you run the check once more
if (is_array ($dat)) {
foreach ($dat AS $k=>$d) {
echo "data for $k is $d";
}
}
else
echo "data for $key is $dat";
}
}
}
}
}
You can use foreach to loop through the arrays which have keys starting from 0 to n. So that you can foreach through the main array to get the datas array for all the keys. For getting rows childs you can use another foreach inside it to get each items. But for rows it is object , so you have to use -> to select the key. see below example code. But on your array the second array consist different formate in rows array. so make it like a common formate to loop through it easily.
For eg :-
foeach($parent_array as $array){
$data=$array['datas'];
$res = $data['res'];
$rows=$data['rows'];
foreach($rows as $row){
echo $row->a; // to get the value of key a = 11
}
}

selecting value of particular index with PHP foreach

I have the following loop that creates an array
while($row1 = mysqli_fetch_assoc($result1))
{
$aliens[] = array(
'username'=> $row1['username'],
'personal_id'=> $row1['personal_id']
);
}
It produces the following result
Array (
[0] =>
Array ( [username] => nimmy [personal_id] => 21564865 )
[1] =>
Array ( [username] => aiswarya [personal_id] => 21564866 )
[2] =>
Array ( [username] => anna [personal_id] => 21564867 )
Then I have another loop as follows, inside which, I need to fetch the personal_id from the above array. I fetch it as follows.
foreach($aliens as $x=>$x_value)
{
echo $aliens['personal_id'];
//some big operations using the
$aliens['personal_id']; variable
}
However, I can't get the values if personal_ids. I get it as null. What seems to be the problem? How can I solve it?
You have an array of "aliens", each alien is an array with personal_id and username keys.
foreach ($aliens as $index => $alien) {
echo $alien['personal_id'], PHP_EOL;
}
The foreach loop iterates its items (aliens). The $alien variable represents the current iteration's item, i.e. the alien array.
foreach($aliens as $x=>$x_value)
{
echo $x_value['personal_id'];
//some big operations using the
$x_value['personal_id']; variable
}

How to output different levels of an array

As a newbie, does anyone have any good tutorials to help me understand different levels of an array? What I'm trying to learn is how to echo different levels, e.g. here is the output array:
Array
(
[meta] =>
Array
(
[total_record_count] => 1
[total_pages] => 1
[current_page] => 1
[per_page] => 1
)
[companies] =>
Array
(
[0] =>
Array
(
[id] => 291869
[url] => https://api.mattermark.com/companies/291869
[company_name] => gohenry.co.uk
[domain] => gohenry.co.uk
)
)
[total_companies] => 1
[page] => 1
[per_page] => 1
)
And here is the code to parse the array:
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
I'm really struggling to find the structure and how to output each items, e.g. tried things like:
echo $item[0]['total_companies'];
echo $item['companies'][0]['id'];
Any help or pointers would be greatly received.
Well, Lets start, You have a multi-dimensional array. For a multi-dimensional array you need to use looping e.g: for, while, foreach. For your purpose it is foreach.
Start with the array dimension, Array can be multi-dimension, Like you have multi-dimension. If you have an array like below, then it is single dimension.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Now, How can you know what is a multi-dimension array, If you array has another array as child then it is called multi-dimensional array, like below.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
Its time to work with your array. Suppose you want to access the value of company_name, what should you do?? Let your array name is $arr.
First you need to use a foreach loop like:
foreach($arr as $key => $val)
The keys are (meta, companies, total_companies...), they are in the first dimension. Now check if the key is company_name or not, if it matches than you got it. Or else you need to make another loop if the $val is an array, You can check it using is_array.
By the same processing at the last element your loop executes and find your value.
Learning
Always a good idea to start with the docs:
arrays: http://php.net/manual/en/language.types.array.php
foreach: http://php.net/manual/en/control-structures.foreach.php
As for tutorials, try the interactive tutorial over at codecademy: https://www.codecademy.com/learn/php
Unit 4 has a tutorial on arrays
Unit 11 has a lesson on advanced arrays.
Your code
As for your code, look at the following which I will show you your array structure and how to access each element. Perhaps that will make things clearer for you.
So lets say your array is named $myArray, see how to access each part via the comments. Keep in mind this is not php code, I'm just showing you how to access the array's different elements.
$myArray = Array
(
// $myArray['meta']
[meta] => Array (
// $myArray['meta']['total_record_count']
[total_record_count] => 1
// $myArray['meta']['total_pages']
[total_pages] => 1
// $myArray['meta']['current_page']
[current_page] => 1
// $myArray['meta']['per_page']
[per_page] => 1
)
// $myArray['companies']
[companies] => Array (
// $myArray['companies'][0]
[0] => Array (
// $myArray['companies'][0]['id']
[id] => 291869
// $myArray['companies'][0]['url']
[url] => https://api.mattermark.com/companies/291869
// $myArray['companies'][0]['company_name']
[company_name] => gohenry.co.uk
// $myArray['companies'][0]['domain']
[domain] => gohenry.co.uk
)
)
// $myArray['total_companies']
[total_companies] => 1
// $myArray['page']
[page] => 1
// $myArray['per_page']
[per_page] => 1
)
As for your for each loop
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
What the foreach loop is doing is looping through each first level of the array $jsonObj, so that would include:
meta
companies
total_companies
page
per_page
Then within the curly braces {} of the foreach loop you can refer to each level by the variable $item.
So depending on what you want to achieve you need to perhaps change your code, what is it you're trying to do as it's not really clear to me.
As for the code within the loop:
echo $item['total_companies'];
It won't work because you're trying to access an array with the index of total_companies within the first level of the $jsonObj array which doesn't exist. For it to work your array would have to look like this:
$jsonObj = array (
'0' => array ( // this is what is reference to as $item
'total_companies' => 'some value'
)
)
What you want to do is this:
foreach($jsonObj as $item)
{
echo $jsonObj['total_companies'];
}
As for your final snippet of code:
echo $item[0]['total_companies'];
Answered this above. Access it like $jsonObj['total_companies'];
echo $item['companies'][0]['id'];
If you want to loop through the companies try this:
foreach($jsonObj['companies'] as $item)
{
// now item will represent each iterable element in $jsonObj['companies]
// so we could do this:
echo $item['id'];
}
I hope that all helps! If you don't understand please make a comment and I'll update my answer.
Please take a look in to here and here
Information about php arrays
Try recursive array printing using this function:
function recursive($array){
foreach($array as $key => $value){
//If $value is an array.
if(is_array($value)){
//We need to loop through it.
recursive($value);
} else{
//It is not an array, so print it out.
echo $value, '<br>';
}
}
}
if you know how deep your array structure you can perform nested foreach loop and before every loop you have to check is_array($array_variable), like :
foreach($parent as $son)
{
if(is_array($son))
{
foreach($son as $grandson)
{
if(is_array($son))
{
foreach($grandson as $grandgrandson)
{
.....
......
.......
}
else
echo $grandson;
}
else
echo $parent;
}
else
echo $son;
}
hope it will help you to understand

PHP how to properly loop through json with multiple levels as object

Here is the Json data stored in variable $json
[Data] => Array
(
[id_number] => Array
(
[value] => 123445567
[link] => 1234556
[class] =>
)
[date] => Array
(
[value] => 04-18-14
[link] => 1234556
[class] =>
)
Currently I access the lower levels like this:
foreach($json['Data'] as $data) {
foreach ($data['id_number'] as $id) {
print $id['value'];
}
}
There is only one result for id_number and only one result for date. Do I really need this second foreach loop? Isn't there a way to access it by just going to the lower level as an object so it would be something like
print $data->id_number->value
Thank you.
Since you have decoded the JSON string as an array you could do
foreach($json['Data'] as $data) {
print $data['id_number']['value'];
}
If you had decoded it into an object (don't set the second parameter to be true) then you could simply do it like you mentioned
foreach($json->Data as $data)
print $data->id_number->value;
Manual
You can retrieve the elements individually (without looping) by:
$id_number = $json['Data']['id_number']['value'];
$date = $json['Data']['date']['value'];
//etc ...
You can use:
$json['Data'][idnr]->value
If you know the id that is ofc, else you will have to loop

Categories