How to put keys in array? - php

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.

Related

Loop not working with assosiative array Php

Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.

Loops returning only one value from array

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];

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.

php remove duplicates based on first value of multidimensional array

Given
[0] => Array
(
[0] => ask.com
[1] => 2320476
)
[1] => Array
(
[0] => amazon.com
[1] => 1834593
)
[2] => Array
(
[0] => ask.com
[1] => 1127456
)
I need to remove duplicate values solely based on first value, regardless of what any other subsequent values may be. Notice [0][1] differs from [2][1] yet I consider this as a duplicate because there are two matching first values. The other data is irrelevant and shouldn't be considered in comparison.
Try this, assuming that $mainArray is the array you have.
$outputArray = array(); // The results will be loaded into this array.
$keysArray = array(); // The list of keys will be added here.
foreach ($mainArray as $innerArray) { // Iterate through your array.
if (!in_array($innerArray[0], $keysArray)) { // Check to see if this is a key that's already been used before.
$keysArray[] = $innerArray[0]; // If the key hasn't been used before, add it into the list of keys.
$outputArray[] = $innerArray; // Add the inner array into the output.
}
}
print_r($outputArray);

Show Can I pull Each Of These Out Of An Array?

I am having trouble pulling elements out of this multi-dimensional array?
Here is my code below:
$ShowTables = $Con->prepare("SHOW TABLES");
$ShowTables->execute();
$ShowTResults = $ShowTables->fetchAll();
If I print_r($ShowTResults); I get this multi-dimensional array:
Array (
[0] => Array ( [Tables_in_alltables] => userinformation [0] => userinformation )
[1] => Array ( [Tables_in_alltables] => users [0] => users )
)
Foreach new table is loaded it adds another dimension of the array. I want to pull each of the table names, out of the multi-dimensional array into a new array which I can use for future plans.
Would anyone have any ideas?
I have tried 1 foreach Loop; but this served no justice.
You want to fetch all results of the first column in form of an array:
$ShowTResults = $Con->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($ShowTResults);
This gives you:
Array (
[0] => userinformation
[1] => users
)
Which I think is what you're looking for.
Another variant (a bit more complicated, but fitting for similar but little different cases) is to fetch the results as function (PDO::FETCH_FUNC) and directly map the result:
$ShowTResults = $ShowTables->fetchAll(PDO::FETCH_FUNC, function($table) {
return $table;
});
A Solution I tried: Perhaps not as other will do, which is in full respect. But Here is mine:
$DatabaseTables = array();
foreach($ShowTResults AS $ShowTResult)
{
foreach ($ShowTResult AS $ShowT)
{
$DatabaseTables[] = $ShowT;
}
}
$DatabaseTables = array_unique($DatabaseTables); //Deletes Duplicates in Array
unset($ShowTResult);
unset($ShowT); // Free up these variables
print_r($DatabaseTables);

Categories