Loops returning only one value from array - php

I have the following array that I converted from a JSON response of the WP REST API:
Array
(
[0] => Array
(
[id] => 6
[convite_id] => Array
(
[0] => 4
)
[nome_do_convidado] => John Doe
[email_do_convidado] => Array
(
[0] => johndoe#gmail.com
)
)
[1] => Array
(
[id] => 5
[convite_id] => Array
(
[0] => 4
)
[nome_do_convidado] => Lorem
[email_do_convidado] => Array
(
[0] => lorem#gmail.com
)
)
)
And I'm trying to loop the [email_do_convidado] value as:
johndoe#gmail.com
lorem#gmail.com
I've tried with foreach() loop and just get the last one, and now I've tried with while() and get one result too, follow my script:
while (list ($key, $val) = each ($myArray) ) echo $val['email_do_convidado'][$key];
And the result is:
johndoe#gmail.com
What I'm doing wrong here?

Try with a foreach instead of a while. You can extract all the emails by merging all arrays into a final output.
$emails = [];
foreach($myArray as $entry){
$emails = array_merge($emails, $entry['email_do_convidado']);
}
var_dump($emails);
I assume you'll want to do something afterwards will all the emails. I'll leave that up to you.

Its not quite clear, what i understand is that u want the first email of each element, if thats the case u could do this
foreach($array as $value){
echo $value[email_do_convidado][0];
}
On the other hand if u have several emails inside "email_do_convidado" u could loop that other array
foreach($array as $value){
foreach($value[email_do_convidado] as $email){
echo $email;
}
}
Or if u dont want to use a foreach inside a foreach u can
//inside the first foreach.
$emails = implode(',', $value[email_do_convidado]);
//and the u echo $emails
echo $emails;
Hope my answer helps u.

The values you are seeking are in:
$myArray[0]['email_do_convidado'][0]
$myArray[1]['email_do_convidado'][0]
Your code is:
while (list ($key, $val) = each ($myArray) ) {
echo $val['email_do_convidado'][$key];
}
(slightly amended to better style)
So your code is trying to retrieve
$myArray[0]['email_do_convidado'][0]
$myArray[1]['email_do_convidado'][1]
The latter doesn't exist. So I'm afraid you have failed on multiple levels:
your code doesn't do what you intend
your error reporting is not working (PHP is throwing a warning about this you are not seeing)
you haven't attempted to instrument your code to see what's happening (simply putting "email=" before the value in your echo statement would have revealed this).
Try:
echo $val['email_do_convidado'][0];

Related

How to check if results from one array are in another array and display the one that isnt?

I have 2 arrays that fetches usernames in a loop. At the end of the loop there should be 1 user that is only in one array, all other users will be in both. I want the output to display the username of the user that is only listed in one of the arrays.
End array example as follows:
$usrArray = Array ( [0] => Dave[1] => Andy[2] => Mike);
$looseArray = Array ( [0] => Dave[1] => Mike);
I want an output to display just "Andy" as he is the only user listed in only 1 array.
Appreciate the help. Thanks.
Like this...
$usrArray = array('Dave','Andy','Mike');
$looseArray = array('Dave','Mike');
foreach ($usrArray as $key => $value) {
if(!in_array($value, $looseArray)){
echo $value;
}
}
https://www.php.net/manual/en/function.array-diff.php
array_diff($usrArray, $looseArray)

How to put keys in array?

I am scrapping details from a certain website. Then I want to parse HTML into a PHP array.
I want to display the array like this. I need to add key so that I can determine easily what data I want to use in the future.
[info] => Array
(
[0] => info1
[1] => info2
)
Here is my code:
$hk = array('info');
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
$hometps[] = $home->plaintext;
}
print_r(array_fill_keys($hk,$hometps));
But output will show me this:
Array
(
[info] => Array
(
[0] => info1
[1] => info2
)
)
Array element cannot stand on its own. Considering you want info as an index, it has to be a part of an array.
If you want the list of info available then assign them to $info variable and when you print_r($info), like this:
$info = array();
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
$info[] = $home->plaintext;
}
print_r($info);
And you will get:
Array
(
[0] => info1
[1] => info2
)
Looks like you might be trying to rename the representation value in the array also known as the 'key' I guess. I recommend doing that directly to the output of the html while going into the foreach. That should solve your issue. It would look something like this(original example at bottom):
$hk = array('info');
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $hk => $home) {
$hometps[] = $home->plaintext;
}
print_r($hometps);
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).
The second form will additionally assign the current element's key to the $key variable on each iteration.
PHP.net:foreach
I think everybody is confused about the issue and question here. The following will give you an array named $info, which will hold the returned values of the foreach loop:
$info = Array();
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
array_push($info,$home->plaintext);
}
print_r($info);
This will output:
Array (
[0] => info1
[1] => info2
)
Hope this was what you were trying to achieve.

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

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

how to get value from array with 2 keys

i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.

Categories