I am running a query that outputs a multidimensional array like this: -
Array
(
[0] => Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)
)
[1] => Array
(
)
[2] => Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)
)
I am trying to make the Array look like this so that we can loop through it on our site: -
Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)
)
This is all being generated using PHP using Symfony2 and Doctrine2. I have tried a couple of methods to get this working but I have reverted back to my first method which is this: -
$companies = array();
foreach($postcodes as $key=>$value) {
$conn = $em->getConnection();
$query = $conn->prepare("SELECT a.id, a.display_name, a.profile_page, b.meta_data FROM companies a, `cms`.pages b WHERE b.slug = a.profile_page AND a.active = 1 AND a.postcode = ".$value." ORDER BY a.display_name ASC");
$execute = $query->execute();
$companies[] = array_replace_recursive($query->fetchAll());
}
echo '<pre>'; print_r($companies); echo '</pre>';
die();
If someone can show me how to get around this, that would be great.
$query->fetchAll() is itself is an multidimensional array you're in need.
Just replace following line
$companies[] = array_replace_recursive($query->fetchAll());
with
$innCompnies=$query->fetchAll();
foreach($innCompnies as $inComp) {
$companies[]=$inComp;
}
It wasn't working because you were pushing multidimensional array into another array. What we actually need to do is to push element one by one into the main array.
I suggest you to avoid SQL-queries in loop. Also you have potential SQL-injection vulnerability concatenating postcodes to your query. So the possible solution may be replacing your foreach loop with something like:
$companies = $conn->fetchAll(
"SELECT a.id, a.display_name, a.profile_page, b.meta_data FROM companies a, `cms`.pages b WHERE b.slug = a.profile_page AND a.active = 1 AND a.postcode IN :postcodes ORDER BY a.display_name ASC",
compact('postcodes')
);
you can transform the multidimentional array like this.
$new_companies = array();
array_walk($companies, function($companie) use($companies, &$new_companies){
if(is_array($companie)) {
foreach ($companie as $c) {
$new_companies[] = $c;
}
}
});
$new_companies is what you want.
Related
So I have the following query:
$resclients=$mysqli->query("SELECT id,client_name FROM clients WHERE id IN ($result[])");
And I am wondering, is it bad practice to execute the above query in a for or foreach-loop, does it hurt the MySQL server?
Or, is it better to do LEFT JOINS or INNER JOINS or RIGHT JOINS?
Forgot to add, the $result[] is actually a two dimensional array.
Show your array:
Array
(
[0] => Array
(
[id] => 7
[resclients] => 6,7,8,9,10,11,12,13,14,15
)
[1] => Array
(
[id] => 5
[resclients] => 5
)
[2] => Array
(
[id] => 4
[resclients] => 4
)
)
Just a small portion of it.
You can use it as:
// a testing multidimensional array
$testArr = array(
array(
'one'=>1,
'two'=>2,
'three'=>3)
);
$yourIds = array();
foreach ($testArr as $value) {
foreach ($value as $finalVal) {
$yourIds[] = $finalVal[];
}
}
$implodedIds = implode(",",$yourIds);
echo "SELECT id,client_name FROM clients WHERE id IN ($implodedIds)";
Result:
SELECT id,client_name FROM clients WHERE id IN (1,2,3)
Note that: this is basic idea how can you use without using query in a loop.
I'm having trouble printing the results of this array in loop (to be displayed on the front end). The objective to be able to get the chapter name (eg, Chapter_Name_Unique), that chapter name's total chapter post views count, and then the fullname of each chapter_member within that chapter name (or group). I'm thinking that something isn't structured properly here, because I'm having issues looping through.
Is my logic off?
print_r looks like this:
Array
(
[Chapter_Name_Unique] => Array
(
[chapter_post_views_count] => 3338
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 3338
[first_name] => Mary
[last_name] => Jane
[fullname] => maryjane
[chapter_name] => Chapter_Name_Unique
)
)
)
[Chapter_Name_Unique_2] => Array
(
[chapter_post_views_count] => 783
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 404
[first_name] => Betty
[last_name] => Lou
[fullname] => bettylou
[chapter_name] => Chapter_Name_Unique_2
)
[1] => Array
(
[post_views_count] => 379
[first_name] => Judy
[last_name] => Jones
[fullname] => judyjones
[chapter_name] => Chapter_Name_Unique_2
)
)
)
)
and the actual functions look like this:
$grouped_types = array();
// to add together post counts of group members
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_post_views_count'] += $chapter['post_views_count'];
}
// to group on top level by chapter_name
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_members'][] = $chapter;
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
Try something like (assuming that $users is your array from your print_r())
$grouped_types = array();
foreach($users as $chapter=>$data){
$grouped_types[$chapter]['chapter_post_views_count'] = $data['chapter_post_views_count'];
foreach($data['chapter_members'] as $member){
$grouped_types[$chapter]['chapter_members'][] = $members['fullname'];
}
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
Thanks so much guys, your tips really helped. I wound up using a bit from both, and pulling this together:
foreach( $grouped_types as $chapter_name_unique => $vars) {
$chapter_post_views = $vars['chapter_post_views_count'];
$chapter_members = $vars['chapter_members'];
echo $chapter_name_unique; // echo chapter name (level 1)
echo $chapter_post_views; // echo chapter post views (level 2 - $vars before)
foreach( $vars['chapter_members'] as $member){ // loop through all chapter_members
$vars['chapter_members'][] = $member['fullname'];
echo $member['fullname']; // echo all usernames within the group
}
}
In combination with the two other foreach statements above (they resort and add things together saving to the $grouped_types array), this works exactly as I needed it to. (Hopefully not too much unnecessary looping?)
Thanks again!
I'm using an API which returns some JSON that I output in PHP.
PHP
$result = $api->sendRequest("getUsers", $inputParameters);
$output = json_decode($result, true);
An example of an array returned by the API. I can print out specific field values fine, but I can't figure out how to write a simple if statement that indicates whether or not there are duplicate names within the query result, specifically duplicate [fullName] fields as seen below.
Array
(
[status] => Array
(
[request] => getUsers
[recordsTotal] => 3
[recordsInResponse] => 3
)
[records] => Array
(
[0] => Array
(
[fullName] => Smith, Tom
[firstName] => Tom
[lastName] => Smith
)
[1] => Array
(
[fullName] => Jones, Bill
[firstName] => Bill
[lastName] => Jones
)
[2] => Array
(
[fullName] => Smith, Tom
[firstName] => Tom
[lastName] => Smith
)
)
)
Any help would be greatly appreciated.
Not tested, but maybe try something like
function dupeCheck($array, $attribute = 'fullName') {
$list = array();
foreach($array['records'] as $value) {
if(in_array($value[$attribute], $list))
return true;
$list[] = $value[$attribute];
}
return false;
}
Just iterating over the records, we maintain a list of values of whatever attribute, once it finds one that was already in the array, returns true.
Then just:
if(!dupeCheck($output, 'fullName')) { // no dupes in the API response }
This should work:
$data['records'] = array_map("unserialize", array_unique(array_map("serialize", $data['records'])));
Taken from here and slightly modified.
Simply create an array whose keys will be the fullnames of the entris you've seen so far:
$names = array();
foreach ($output['records'] as $entry){
If (isset($names[$entry['fullname']]){
// do some error processing
echo "'${entry['fullname']}' is a duplicate";
}
$names[$entry['fullname']] = $entry;
}
You should have all the unique entries in $names.
PHP has a lot of built in array functions to help with operations like this. You could try the following:
$names = array_column($output['records'], "fullName");
if(count(array_unique($names)) < count($names)) {
... /* handle duplicate values here */
}
In addition, $names contains a unique array of all the fullName columns from the original array for easy access and traversing. You can use this inside the above if statement to determine which names are duplicates like so:
$names_count = array_count_values($names);
foreach($names_count as $key => $value) {
if(value > 1) {
$dupes[] = $key;
}
}
References:
PHP Array Functions
array_column()
array_unique()
array_count_values()
I have created an array, as follows:
$results = array();
do {
$results[] = $row_products;
} while ($row_products = mysql_fetch_assoc($products));
print_r($results);
This prints out the array like this:
Array (
[0] => Array (
[productName] => product1
)
[1] => Array (
[productName] => product2
)
[2] => Array (
[productName] => product3
)
I want to now use say the second item in the array in another mysql query.
But I cannot define it. I have tried
$results[1];
but this does not work.
So in effect, if I echo the second item, it would print 'product2'.
You should learn the basics about arrays here: http://www.php.net/manual/en/language.types.array.php
You are using a nested array, so you have the access it like this:
echo $results[1]['productName'];
Another solution would be to use $results[] = $row_products['productName']; and then just echo $results[1].
In addition, you should use a while loop instead of a do/while loop because $row_products does not seem to be defined for the first iteration.
while ($row_products = mysql_fetch_assoc($products)) {
$results[] = $row_products;
}
try this :
echo $results[1]['productName'] ;
$results[1] is an array, If you want see the array print_r($results[1]);
I have an array that looks like the one below. I'm trying to group and count them, but haven't been able to get it to work.
The original $result array looks like this:
Array
(
[sku] => Array
(
[0] => 344
[1] => 344
[2] => 164
)
[cpk] => Array
(
[0] => d456
[1] => d456
)
)
I'm trying to take this and create a new array:
$item[sku][344] = 2;
$item[sku][164] = 1;
$item[cpk][d456] = 1;
I've gone through various iterations of in_array statements inside for loops, but still haven't been able to get it working. Can anyone help?
I wouldn't use in_array() personally here.
This just loops through creating the array as it goes.
It seems to work without needing to first set the index as 0.
$newArray = array();
foreach($result as $key => $group) {
foreach($group as $member) {
$newArray[$key][$member]++;
}
}