PHP Manipulate associative array - php

I'm using PHP in doing our exercise which is to get the necessary details of a user and the quiz he/she took.
This is my code so far.
<?php
require("dbOption/Db.class.php");
$db = new Db();
$data = array();
$quiz = array();
$easy = "";
$normal = "";
$hard = "";
// SELECT id, course FROM quizz WHERE course = 2
$res_quizz = $db->query("SELECT id, course FROM quizz WHERE course = :course", array("course"=>2));
foreach ($res_quizz as $key => $value) {
$quizzid = $value['id'];
// SELECT easy, normal, hard, userid FROM quizzscore WHERE quizid = $quizid
$res_quizzscore = $db->query("SELECT easy, normal, hard, userid, quizzid FROM quizzscore WHERE quizzid = :quizzid", array("quizzid"=>$quizzid));
foreach ($res_quizzscore as $key => $value2) {
$easy = $value2['easy'];
$normal = $value2['normal'];
$hard = $value2['hard'];
$quizzid = $value2['quizzid'];
$userid = $value2['userid'];
$q = array(
'Qz'.$quizzid => array(
'easy' =>$easy,
'normal' =>$normal,
'hard' =>$hard,
)
);
$quiz['quizzes'] = $q;
// SELECT name FROM USER WHERE id = $userid
$res_user = $db->query("SELECT name FROM user WHERE id = :id", array("id"=>$userid));
foreach ($res_user as $key => $value3) {
$name = $value3['name'];
}
}
$data[$userid] = array();
$data[$userid]['name'] = $name;
$data[$userid]['quizzes'] = $quiz;
echo "<pre>";
print_r($data);
echo "<pre/>";
}
The array is poorly manipulated and that's why I'm getting this result.
Array
(
[1] => Array
(
[name] => John Smith
[quizzes] => Array
(
[quizzes] => Array
(
[Qz1] => Array
(
[easy] => 5
[normal] => 6
[hard] => 7
)
)
)
)
)
Array
(
[1] => Array
(
[name] => John Smith
[quizzes] => Array
(
[quizzes] => Array
(
[Qz2] => Array
(
[easy] => 3
[normal] => 4
[hard] => 5
)
)
)
)
)
What I want to have is this kind of result.
Array
(
[1] => Array
(
[name] => John Smith
[quizzes] => Array
(
[quizzes] => Array
(
[Qz1] => Array
(
[easy] => 5
[normal] => 6
[hard] => 7
)
[Qz2] => Array
(
[easy] => 3
[normal] => 4
[hard] => 5
)
)
)
)
)
Any ideas would be most appreciated.

Related

two dimensional array to Update into mysql database

I have this array:
Array (
[0] => Array
(
[0] => 2
)
[1] => Array
(
[0] => 2015-07-20
)
[2] => Array
(
[0] => 2
[1] => 5
)
[3] => Array
(
[0] => 70
[1] => 17
)
[4] => Array
(
[0] => 4
[1] =>
)
[5] => Array
(
[0] => 66
[1] => 17
)
)
Now I want Update to database like this
Array
(
[0] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 2
[3] => 70
[4] => 4
[5] => 66
)
[1] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 5
[3] => 17
[4] =>
[5] => 17
)
)
Is it possible? Or qny other way to UPdate record from array?
I have foreach loop OUTPUT like this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 item_id =5 before_sale_totitem_qty =70 before_sale_totitem_qty =17 after_sale_totitem_qty =4 after_sale_totitem_qty = restOfItem =66 restOfItem =17 note =NULL WHERE shop_id =2
But I Want to this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 before_sale_totitem_qty =70 after_sale_totitem_qty =4 restOfItem =66 note =NULL WHERE shop_id =2
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =5 before_sale_totitem_qty =17 after_sale_totitem_qty = restOfItem =17 note =NULL WHERE shop_id =2
Any help?
If i understand your question you need transform data from first array to second array and after you can make this foreach?
If yes there is transform to array with default values from 0 index. Works for multiple versions so you can add index 3,5, etc. and it will works still.
$default = array();
$versions = array();
foreach($array as $key => $values){
foreach($values as $version => $value){
if($version === 0){
$default[$key] = $value;
continue;
}
if(!array_key_exists($version, $versions)){
}
$versions[$version][$key] = $value;
}
}
$return = array(
0 => $default,
);
foreach($versions as $version => $versionData){
$return[$version] = $versionData+$default;
}
If you need foreach to build your SQL query it is here to:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnData = array();
foreach($data as $columnIndex => $value){
$columnData[] = sprintf('%s = %s', $columns[$columnIndex], $value);
}
$sql = sprintf('UPDATE update_shopwise_stock SET %s WHERE shop_id=%d', implode(', ', $columnData), $data[0]);
}
But my personal recommendation is not use sql like this, but use PDO for prepare statement and better security. For prepare statement is for loop here:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnPrepare = array();
$columnData = array();
foreach($data as $columnIndex => $value){
$columnName = $columns[$columnIndex];
$columnPrepare[] = sprintf('%s = :%s', $columnName, $columnName);
$columnData[$columnName] = $value;
}
$query = $db->prepare(sprintf("UPDATE update_shopwise_stock SET %s WHERE shop_id=:shop_id", implode(', ', $columnPrepare)));
foreach($columnData as $column => $value){
$query->bindParam(sprintf(':%s', $column), $value);
}
$query->execute();
}
Everything is untested and can have some bugs, eventually performance issue. It is based on question issue and show only way how to solve this issue.

Merge arrays from one string?

I am having trouble with trying to merge mulitple arrays into one array I also cant seem to find a decent solution to this problem since using merge_array doesnt work. I made an array in my foreach loop but it keeps coming out as multiple arrays for one string. How can I convert this.
Array
(
[images] => /wp-content/uploads/2015/03/223-HfpWJ4h.jpg
[userid] => 15
)
Array
(
[images] => /wp-content/uploads/2015/03/074-XlqzqVn.jpg
[userid] => 1
)
Array
(
[images] => /wp-content/uploads/2014/09/cj-spiller.jpg
[userid] => 1
)
Array
(
[images] => /wp-content/uploads/2015/02/183-cZRn9rz.jpg
[userid] => 1
)
Array
(
[images] => /wp-content/uploads/2015/02/001-gSxGEWD5.jpg
[userid] => 1
)
To this?
Array
(
[0] => array(
[images] => /wp-content/uploads/2015/03/223-HfpWJ4h.jpg
[userid] => 15
)
[1] => array(
[images] => /wp-content/uploads/2015/03/074-XlqzqVn.jpg
[userid] => 1
)
[2]=> array(
[images] => /wp-content/uploads/2014/09/cj-spiller.jpg
[userid] => 1
)
)
This is my code
global $wpdb, $bp;
$activity_table = bp_core_get_table_prefix() . 'bp_activity';
$activity_meta_table = bp_core_get_table_prefix() . 'bp_activity_meta';
// that have pictures associated with them
$sql = "SELECT a.*, am.meta_value, am2.meta_value as privacy FROM $activity_table a
INNER JOIN $activity_meta_table am ON a.id = am.activity_id
LEFT JOIN (SELECT activity_id, meta_key, meta_value FROM $activity_meta_table
WHERE meta_key = 'activityprivacy') am2 ON a.id = am2.activity_id
AND (am.meta_key = 'buddyboss_pics_aid' OR am.meta_key = 'bboss_pics_aid')
ORDER BY a.date_recorded DESC";
$pics = $wpdb->get_results($sql,ARRAY_A);
$i = 0;
foreach($pics as $pic){
$attachment_id = isset($pic['meta_value']) ? (int)$pic['meta_value'] : 0;
$tn = wp_get_attachment_image_src( $attachment_id, 'buddyboss_pic_tn' );
$userid = $pic['user_id'];
if($tn[0] != ''){
$profile_image = array('images' => $tn[0], 'userid' => $pic['user_id']);
print_r($profile_image);
}
}
It seems like:
$result = array();
//...
foreach($pics as $pic){
//...
$userid = $pic['user_id'];
if($tn[0] != ''){
$profile_image = array('images' => $tn[0], 'userid' => $pic['user_id']);
$result[] = $profile_image;
}
}
Isn't it? Or I've mistaken your purpose.

Inserting data to mysql from .xml php array

Im trying to get some data from the LinkedIn API using OAuth 2.0. I've got the data insert for name done, but i can't seem to get the skills values. If tried to implode the data but it doesnt find any data. I know the data is recieved.
My code:
<?php
session_start();
require_once('oAuth/config.php');
require_once('oAuth/linkedinoAuth.php');
require_once('oAuth/class.linkedClass.php');
$linkedClass = new linkedClass();
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret']);
//$linkedin->debug = true;
if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
}
else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);
}
$content1 = $linkedClass->linkedinGetUserInfo($_SESSION['requestToken'], $_SESSION['oauth_verifier'], $_SESSION['oauth_access_token']);
$xml = simplexml_load_string($content1);
$array = XML2Array($xml);
$content = array($xml->getName() => $array);
/* Info */
$firstname = $array['first-name'];
$lastname = $array['last-name'];
$email = $array['email-address'];
$headline = $array['headline'];
$picurl = $array['picture-url'];
$publicprofileurl = $array['public-profile-url'];
$summary = $array['summary'];
$numconnections = $array['num-connections'];
/* SKIILS */
$skills = $array['skills']->skill->skill->name;
function XML2Array(SimpleXMLElement $parent)
{
$array = array();
foreach ($parent as $name => $element) {
($node = & $array[$name])
&& (1 === count($node) ? $node = array($node) : 1)
&& $node = & $node[];
$node = $element->count() ? XML2Array($element) : trim($element);
}
return $array;
}
?>
The arrays:
Array
(
[person] => Array
(
[id] => ########
[first-name] => ########
[last-name] => ########
[languages] => Array
[skills] => Array
(
[skill] => Array
(
[id] => 1
[skill] => Array
(
[name] => Start-ups
)
[0] => Array
(
[id] => 2
[skill] => Array
(
[name] => Business Strategy
)
)
[1] => Array
(
[id] => 3
[skill] => Array
(
[name] => Marketing Strategy
)
)
[2] => Array
(
[id] => 12
[skill] => Array
(
[name] => Management
)
)
)
)
[email-address] => ########
[phone-numbers] => ########
[im-accounts] => ########
[twitter-accounts] => ########
[headline] => ########
[picture-url] => ########
[public-profile-url] => ########
)
)
These are many multiple array try that :
$person=$array["person"]; // $person is array
//get first array values
$firstname = $person['first-name'];
$lastname = $person['last-name'];
$email = $person['email-address'];
$headline = $person['headline'];
$picurl = $person['picture-url'];
$publicprofileurl = $person['public-profile-url'];
$skills=$person["skills"]; //$skills is array
$skills_inner=$skills["skill"]; //skills_inner is array
//get $skills_inner value (id)
$id=$skills_inner["id"];
$skills_inner_2=$skills_inner["skill"]; // $skills_inner_2 is array
// get $skills_inner_2 value (name)
$name=$skills_inner_2["name"];
Good Luck.

Two Array's Trying to Combine where A Value is equal to a key?

I Have Two Array's One That is a 'App' Array and one is a 'Table' Array. Each Row in 'Table' has an 'AppID' As Shown Below. How can I combine the array to where the App_ID in the Tables Array is under the Same App_ID on the App Array? What I Currently Have is First and Want I Want is after that. I am using PHP. Thank Your for all of the Help!
App Array:
Array
(
[1] => Array
(
[App_ID] => 1
[App_Name] => Project Manager
[App_Created] => 2014-12-17 16:31:57
)
[2] => Array
(
[App_ID] => 2
[App_Name] => Estimating
[App_Created] => 2014-12-17 23:49:40
)
)
Tables Array:
Array
(
[1] => Array
(
[Table_ID] => 1
[App_ID] => 1
[Table_Name] => Customers
)
[2] => Array
(
[Table_ID] => 2
[App_ID] => 1
[Table_Name] => Jobs
)
)
I Want to Go to:
Array
(
[1] => Array
(
[App_ID] => 1
[App_Name] => Kennedy_Fabricating_Project_Manager
[App_Created] => 2014-12-17 16:31:57
[Tables] = > Array
(
[Table_ID] => 1
[App_ID] => 1
[Table_Name] => Customers
),
Array
(
[Table_ID] => 2
[App_ID] => 1
[Table_Name] => Jobs
)
)
[2] => Array
(
[App_ID] => 2
[App_Name] => Estimating
[App_Created] => 2014-12-17 23:49:40
)
)
My Current PHP Code:
//Get App List
$apps_sql = $conn->query("SELECT * FROM `Apps`") or die("Conn Query Apps Failed");
$apps = array();
while($apps = $apps_sql->fetch_array(MYSQLI_ASSOC)) {
$app_id = $apps['App_ID'];
$table_sql = $conn->query("SELECT * FROM `Tables` WHERE `App_ID` = $app_id") or die("Conn Query Tables in Apps Failed");
// My Guess is Something Here?
$apps_a[$app_id] = $apps;
}
// Table List
$table_sql = $conn->query("SELECT * FROM `Tables`") or die("Conn Query Tables Failed");
$tables = array();
while($tables = $table_sql->fetch_array(MYSQLI_ASSOC)) {
$table_id = $tables['Table_ID'];
$tables_a[$table_id] = $tables;
}
It looks cleaner, and faster as you make only 2 queries instead of zillions
$apps_sql = $conn->query("SELECT * FROM `Apps`");
$apps_ids = array();
while ($app = $apps_sql->fetch_array(MYSQLI_ASSOC))
{
$apps_ids[] = $app['App_ID'];
$apps[$app['App_ID']] = $app;
}
$apps_ids = implode(',', $apps_ids);
$table_sql = $conn->query("SELECT * FROM `Tables` WHERE IN ({$apps_ids})");
while($table = $table_sql->fetch_array(MYSQLI_ASSOC))
{
$apps[$table['App_ID']]['tables'][] = $table;
}
just change:
$table_id = $tables['Table_ID'];
$tables_a[$table_id] = $tables;
into:
$apps_a[$tables['App_ID']]['Tables'][$tables['Table_ID']] = $tables;

php array flip value as key and make it simple

i have been troubling to format array correctly
i have this code:
require('simple_html_dom.php');
$table = array();
$html = file_get_html('apc.html');
foreach($html->find('tr') as $row) {
$rack = ltrim($row->find('td',0)->plaintext);
$location = ltrim($row->find('td',1)->plaintext);
$usage = ltrim($row->find('td',2)->plaintext);
$auk = ltrim($row->find('td',3)->plaintext);
$cost = ltrim($row->find('td',4)->plaintext);
$rack = rtrim($rack);
$location = rtrim($location);
$usage = rtrim($usage);
$auk = rtrim($auk);
$cost = rtrim($cost);
$table[$rack][$usage][$auk][$cost] = true;
}
echo '<pre>';
print_r($table);
echo '</pre>';
using simple_html_dom above i can convert html table to an array as follow:
[Rack01] => Array
(
[741,60] => Array
(
[1.409,04] => Array
(
[267,72] => 1
)
)
[110,88] => Array
(
[210,67] => Array
(
[40,03] => 1
)
)
)
[Rack 09] => Array
(
[843,84] => Array
(
[1.603,30] => Array
(
[304,63] => 1
)
)
)
I would like to have result as below:
array(
[0] => array (
[usage] => 'Rack 01',
[usage] => '741,60',
[auk] => '1.409.04',
[cost] => '267,72')
[1] => array (
[usage] => 'Rack 02',
[usage] => 'value???',
[auk] => 'value???',
[cost] => 'value???')
any help would be apreaciate
Something like this. Also note that trim will do both left and right:
foreach($html->find('tr') as $row) {
$rack = trim($row->find('td',0)->plaintext);
$location = trim($row->find('td',1)->plaintext);
$usage = trim($row->find('td',2)->plaintext);
$auk = trim($row->find('td',3)->plaintext);
$cost = trim($row->find('td',4)->plaintext);
$table[] = array('rack' => $rack,
'usage' => $usage,
'auk' => $auk,
'cost' => $cost);
}

Categories