how to merge these 2 arrays (php+sql) - php

I have 2 arrays, both from a SQL query, each from a different database. Since it's not possible to merge these 2 SQL queries into 1 query to get 1 array (due to some restrictions), I am forced to combine the 2 arrays. Problem is, I can't seem to get this working.
This is array 1:
echo '<ul id="friends">';
foreach($result as $friend => $value)
{
echo '<li><img src="'.$value['pic_square'].'" alt="" />'.$value['uid'].' ' . $value['name'] . '</li>';
}
echo '</ul>';
And will output:
picture 12345 Dave
picture 67890 Mike
Etc
This is array 2:
echo '<ul id="friends">';
while($value = mysql_fetch_array($query))
{
echo '<li> '.$value['fbid'] .' '. $value['userphone'] .'</li>';
}
echo '</ul>';
And will output:
12345 020-12345
67890 020-56789
Etc
What do I need? I want to merge these 2 arrays so that the phonenr from array 2 will be added behind the username from array 1.
Example what the output should look like:
picture Dave 020-12345
picture Mike 020-56789
Etc
fbid and uid are the id's to link each other, but are not shown in the combined array.
Hope someone knows how to do this!
Kind regards,
Maurice

This is the simplest and most efficient way I could think of doing it. The foreach loop iterates through your first array and basically add new key/value pairs using the "uid" as the key. This will enable you to easily find them when you loop through the second query's results.
<?php
// First query.
foreach ( $result as $key => $value )
{
// Add a new key/value pair in the array using the "uid" as the key and $value as the value.
$result[$value['uid']] = $value;
// Remove the previous key/value pair value.
unset($result[$key]);
}
// Second query.
while ( $value = mysql_fetch_array($query) )
echo sprintf('<li>%s %s %s</li>', $result[$value['fbid']]['pic_square'], $result[$value['fbid']]['name'], $value['userphone']);

As the array collection names are different (different column name) I am not sure direct merging will work.
$result = array_merge($result, $query);
print_r($result);
But you can work around like below.
Give loops and store in a third array from both the arrays and do necessary actions on third array.

Related

Get Records From Array Based On Value

Bottom line, I have a huge multidimensional array returned by ldap_get_entries that I am trying to parse into different groups based on the location attribute.
In PowerShell I could do something like:
$location1 = Get-ADUser -Filter * | ? {?_.l -eq "test_location"}
What I am currently doing within PHP (as far as my brain will let me go) is something like:
Foreach ($records as $record) {
if (isset($record['l'])) {
switch ($record['l'][0]) {
case "test_location1":
$location1[] = $record;
continue 2;
case "test_location2":
$location2[] = $record;
continue 2;
}
}
}
I then use a foreach loop (alternative syntax) against an array of location variables ($location1, $location2), that I used the above method, to sort records into their appropriate location variable. In this way, I build an HTML table grouping each locations records together. I build a new table for each location with some HTML code in between each group, so I don't believe sorting the ldap results by location will work, as it would output one large table.
Is there any way to specify a WHERE clause in PHP? So that I can assign all records in an array with a matching key value to variable1 and all records in an array with a different matching key value to variable2.
I am assuming I am tackling this in an amateur scripting way.. If there is an easier way to accomplish this task (maybe skipping the assign records to variables part), or any sort of "best practice" I am missing here, I am up for learning it.
Thanks in advance!!
As far as I understood your question you want something like this:
$recordsSorted = array();
foreach ($records as $record) {
if (! isset($record['l'])) {
continue;
}
$recordsSorted[$records['l'][0]][] = $record;
}
ksort($recordsSorted);
foreach($recordsSorted as $location => $records) {
usort($records, function($a, $b){
return strnatcasecmp($a['uid'][0], $b['uid'][0]);
});
echo '<h1>$location</h1><ul>';
foreach ($records as $record) {
echo '<li>' . $record['dn'] . '</li>';
}
echo '</ul>';
}
This will first put the first entry to the location-attribute of an entry as key of an array. That key can then be used to sort the array.
To output the content then it iterates over the new array and sorts the content - in this case using the first value of the uid-attribute (change the uid to whatever attribute you need). This sorted content is then output to HTML.
the first array $recordsSorted might look somewhat like this:
array(
'London' => array(
array(<entry from the LDAP>),
array(<another entry from LDAP>),
),
'Paris' => array(
array(<a further entry from the LDAP>),
),
'Berlin' => array(
array(<and even another entry from the LDAP>),
),
);
The result would then look somewhat like this:
<h1>Berlin</h1>
<ul>
<li>[UID of and even another entry from the LDAP]</li>
</ul>
<h1>London</h1>
<ul>
<li>[UID of another entry from LDAP]</li>
<li>[UID of entry from the LDAP]</li>
</ul>
<h1>Paris</h1>
<ul>
<li>[UID of a further entry from the LDAP]</li>
</ul>
Does that look like it could help you?

How to get the values inside an array?

$playerId= array();
$playerId[] = intval($row['Id']);
$allrounders[] = array(
'Weight'=>$fullTotal,
'Id'=>$playerId
);
rsort($allrounders);
$sliceAr = array_slice($allrounders,0,5);
foreach($sliceAr as $allroundK){
echo $allrounders[]['Id']."<br/>";
}
Question:
In the above array how to get the values of the Id Key accordingly? It takes all the player scores and organizes that with his ID and sorts it descending order. It takes the 1st 5 results. I need the Ids of those.
Inside the foreach loop, $allroundK is the item of your array. In this case, it's the array with weight and id. So:
foreach($sliceAr as $allroundK) {
echo $allroundK['Id']."<br />";
}
Do
echo $allrounders[0]['Id'][0];
Since you have set the array in this manner
$allrounders[] = array(
'Weight'=>$fullTotal,
'Id'=>$playerId
);
Here $allrounders[] also means that an array so the elements Weight and Id will be added in the [0th] element of the array $allrounders
If you want to get rid of [0] just set the array like this
$allrounders = array(
'Weight'=>$fullTotal,
'Id'=>$playerId
);
And now you can access the Id like
echo $allrounders['Id'][0];
EDIT:
In your case it will work as
foreach($sliceAr as $allroundK){
echo $allroundK['Id'][0]."<br/>";
}
or
foreach($sliceAr as $allroundK){
foreach($allroundK['Id'][0] as $allroundJ){
echo $allroundJ."<br/>";
}
}

Getting key from array without looping when there is only one record

$array['2']['21'] = null;
I want to get 21 from array above without looping, is it possible? I want to do it for those arrays which have ONLY 1 record in them. Obviously I'll have to use loop for others.
foreach ($array['2'] as $key => $value)
{
echo $key;
//I know this does the job wondering if there is simple function
}
I looked at extract() but doesn't do my job.
try this :
$arr_keys = array_keys($array['2']);
echo "<pre>";
print_r($arr_keys);
Ref: http://php.net/manual/en/function.array-keys.php

Breaking a MultiDimensional Array into a Single Dimension

I have fields in mySQL which is currently being stored like this under the field "tags"
Shopping|Health & Beauty
Coffee|Shopping
What I'm trying to do is to loop through this to create a single dimension array and to grab only the unique values.
I have my query selecting DISTINCT tags from TABLE and run the loop like this:
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
}
echo "<pre>";
print_r($imploded_tags);
The result from the print_r is showing it as a multidimensional array. I've tried to reexplode it and implode it in different ways, but I haven't been able to get any success. Is there a way that I can create this into a single dimension array? Not all tags will have an equal amount of tags separated by |, so I can't seem to get it to go with a function that I tried from another StackOverflow post. Any help would be greatly appreciated!
OUTPUT:
Array
(
[0] => Array
(
[0] => Shopping
[1] => Health & Beauty
)
[1] => Array
(
[0] => Coffee
[1] => Shopping
)
try this
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$tags = explode("|",$tags);
foreach($tags as $v){
$imploded_tags[] = $v;
}
}
I would do something like:
$imploded_tags = array_merge(explode("|",$tags), $imploded_tags);
}
$imploded_tags = array_unique($imploded_tags);
echo "<pre>";
print_r($imploded_tags);
See the manual on array_merge and array_unique.
However, I do think you are not using the right way to store your tags; they should be stored in a separate table as separate values.
What's going on is when you're fetching your rows from MySQL, you're essentially getting a bunch of data in an array in the first place, which is why you have to loop through them.
With your your implode function, you're taking a bunch of strings, then getting another array set and then appending that to an external array.
If you really wanted to get a single dimensional array without having this multidimensional thing going on, all you really need to do is utilize another loop within that loop.
$all_tags = array();
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
for($i = 0; $i < count($imploded_tags); $i++) {
$all_tags[] = $imploded_tags[$i]
}
}
print_r($all_tags);

How to access mysql result set data with a foreach loop

I'm developing a php app that uses a database class to query MySQL.
The class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/*note there are multiple bad practices demonstrated in the tutorial -- it should not be used as a modern guide!
I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one).
When using select() it returns a multidimensional array that has rows with 3 associative columns (id, firstname, lastname):
Array
(
[0] => Array
(
[id] => 1
[firstname] => Firstname one
[lastname] => Lastname one
)
[1] => Array
(
[id] => 2
[firstname] => Firstname two
[lastname] => Lastname two
)
[2] => Array
(
[id] => 3
[firstname] => Firstname three
[lastname] => Lastname three
)
)
Now I want this array to be used as a mysql result (mysql_fetch_assoc()).
I know that it may be used with foreach(), but this is with simple/flat arrays. I think that I have to redeclare a new foreach() within each foreach(), but I think this could slow down or cause some higher server load.
So how to apply foreach() with this multidimensional array the simplest way?
You can use foreach here just fine.
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
I think you are used to accessing the data with numerical indices (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.
You can use array_walk_recursive:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
This would have been a comment under Brad's answer, but I don't have a high enough reputation.
Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.
In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows
foreach ($mda as $mdaKey => $mdaData) {
echo $mdaKey . ": " . $mdaData["value"];
}
Hope that helps someone.
Holla/Hello,
I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.
for ($i = 0 ; $i < count($files['name']); $i++) {
echo $files['name'][$i].'<br/>';
}
It is tested on my PC.
To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:
$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);
Then use a foreach loop and have the array ran through like this:
foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}
You can echo whatever you like around it to, so to echo into a table:
echo "<table>"
foreach ($example_array as $value) {
echo "<tr><td>" . $value[0] . "</td>";
echo "<td>" . $value[1] . "</td>";
echo "<td>" . $value[2] . "</td></tr>";
}
echo "</table>";
Should give you a table like this:
|1|John|Smith |
|2|Dave|Jones |
|3|Bob |Williams|
Example with mysql_fetch_assoc():
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach, with the $result array you get from select():
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
I know this is quite an old answer.
Here is a faster solution without using foreach:
Use array_column
print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'
Also you can check before executing the above operation
if(array_key_exists('firstname', $array)){
print_r(array_column($array, 'firstname'));
}
Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?
when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.
That should be the same as mysql_fetch_assoc would give (in a loop) for each row.
foreach ($parsed as $key=> $poke)
{
$insert = mysql_query("insert into soal
(pertanyaan, a, b, c, d, e, jawaban)
values
('$poke[question]',
'$poke[options][A]',
'$poke[options][B]',
'$poke[options][C]',
'$poke[options][D]',
'$poke[options][E]',
'$poke[answer]')");
}
If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.
In this usage, I have this array with each element needing an appended comma and newline.
$some_array = [];
data in $some_array
0: "Some string in an array"
1: "Another string in an array"
Per php.net
If callback needs to be working with the actual values of the array,
specify the first parameter of callback as a reference. Then, any
changes made to those elements will be made in the original array
itself.
array_walk_recursive($some_array, function (&$value, $key) {
$value .= ",\n";
});
Result:
"Some string in an array,\n"
"Another string in an array,\n"
Here's the same concept using array_walk to prepend the database table name to the field.
$fields = [];
data in $fields:
0: "FirstName"
1: "LastName"
$tbl = "Employees"
array_walk($fields, 'prefixOnArray', $tbl.".");
function prefixOnArray(&$value, $key, $prefix) {
$value = $prefix.$value;
}
Result:
"Employees.FirstName"
"Employees.LastName"
I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.
A mysql result set object is immediately iterable within a foreach(). This means that it is not necessary to call any kind of fetch*() function/method to access the row data in php. You can simply pass the result set object as the input value of the foreach().
Also, from PHP7.1, "array destructuring" allows you to create individual values (if desirable) within the foreach() declaration.
Non-exhaustive list of examples that all produce the same output: (PHPize Sandbox)
foreach ($mysqli->query("SELECT id, firstname, lastname FROM your_table") as $row) {
vprintf('%d: %s %s', $row);
}
foreach ($mysqli->query("SELECT * FROM your_table") as ['id' => $id, 'firstname' => $firstName, 'lastname' => $lastName]) {
printf('%d: %s %s', $id, $firstName, $lastName);
}
*note that you do not need to list all columns while destructuring -- only what you intend to access
$result = $mysqli->query("SELECT * FROM your_table");
foreach ($result as $row) {
echo "$row['id']: $row['firstname'] $row['lastname']";
}

Categories