Not able to generate a chart-php - php

I am creating bar chart , i am unable to get output and generate chart.
here is my code
if ($sql) {
$arrData = array(
"chart" => array(
"caption" => "Status stastics",
"showValues" => "0",
"theme" => "zune"
)
);
$arrData["data"] = array();
foreach($sql as $row) {
array_push($arrData["data"], array(
"label" => $row["name"],
"value" => $row["value"]
)
var_dump($row["value"]);
);
}
}
I am not getting any output for ( var_dump($row["value"]);)
am i going in a right way?
Can any one help me in this.

Got my answer
if ($sql) {
$arrData = array(
"chart" => array(
"caption" => "Status stastics",
"showValues" => "0",
"theme" => "zune"
)
);
$arrData["data"] = array();
foreach($sql as $row)
{
$object_array =(array)$row;
array_push($arrData["data"], array(
"label" => $object_array["name"],
"value" => $object_array["value"]
)
);
}
}
?>

Related

Add elements to an array to be used in another array

I have the following code:
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => array( "usa", "canada" )
)
)
) );
I also have a loop above to identify all of the "terms" like this:
$term_list = get_the_terms($post->ID,$taxonomy);
foreach($term_list as $term_single) {
echo $term_single->slug; //do something here
}
I'd like to dynamically replace "usa" and "canada" with the results from my foreach loop. How can I do that?
You should do something like that
function getTermsForQuery($post) {
$result = [];
$term_list = get_the_terms($post->ID,$taxonomy);
foreach($term_list as $term_single) {
$result[] = $term_single->slug; //do something here
}
return $result;
}
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => getTermsForQuery($post)
)
)
) );
Without foreach Loop
$term_list = get_the_terms($post->ID,$taxonomy);
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => $term_list
)
)
) );
With foreach loop
$term_list = get_the_terms($post->ID,$taxonomy);
foreach($term_list as $term_single) {
$cat_terms[] = $term_single;
}
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => $cat_terms
)
)
) );
I have create 3 arrays then fill each one and insert to another.
//for loop, store the values that you want
$subArray2 = array();
for($row = 0;$row < 3;$row++){
$subArray2[$row] = "Value_$row";
}
$subArray1 = array("taxonomy" => "country","field" => "slug","terms" => $subArray2);
$arr = array("tax_query" => $subArray1);
//var_dump($arr);
foreach($arr as $val){
foreach($val as $val1){
if(is_array($val1)){
foreach($val1 as $val2){
echo "$val2<br>";
}
}else{
echo $val1 . "<br>";
}
}
}

php - How to insert a foreach loop inside a multidimensional array

How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.
You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';

Extracting from mulit-array and putting it into my own - php

I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.
You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);
You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];

Just cant get the for loop to produce needed array in Php

I need my for loop to return an array that looks like this
$nullArray =array(
0 => array("id" => 1, "label" => "test 1", "type" => "folder"),
array("id" => 2, "label" => "test 2", "type" => "folder"),
array("id" => 3, "label" => "test 3", "type" => "folder"),
etc...
etc...
etc...
);
what I have right now
$nullArray = array();
$numOfVer = mysql_num_rows($result);
$startArray= array();
//SETS FIRST NODE
for($i =0;$i < $numOfVer;$i++)
{
$label = mysql_result($result, $i);
$id = $i+1;
$startArray = array(array('id' => $id,'label' => $label, "type" => "folder"));
//$startArray[]['id'] = $id;
//$startArray[]['label'] = $label;
//$startArray[]['type'] = "folder";
//array_push($startArray,array(array('id' => $id,'label' => $label, "type" => "folder")));
//$nullArray[0]= array(array('id' => $id,'label' => $label, "type" => "folder"));
//array_push($nullArray[0],array('id' => $id,'label' => $label, "type" => "folder"));
}
$nullArray[0] = $startArray;
echo json_encode($nullArray[0]);
Everything that I have commented out is something that I have tried and it has failed. I'v been at it for too long for something so simple so I decided to get some help! Thank you in advance! :)
In for loop you are redclaring your $startArray thats why the previous value removed. Try this.
$nullArray = array();
$numOfVer = mysql_num_rows($result);
$startArray= array();
for($i =0;$i < $numOfVer;$i++)
{
$label = mysql_result($result, $i);
$id = $i+1;
$startArray[] = array('id' => $id,'label' => $label, "type" => "folder");
}

Put nested array into one array

Suppose i have a array like this :
Array(
'1' => Array(
"ID" => 1,
"Name" => "name 1"
),
'2' => Array (
Array(
"ID" => 2,
"Name" => "name 2"
)
),
'3' => Array(
Array(
Array(
Array(
"ID" => 3,
"Name" => "name3"
)
)
),
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
number of sub-arrays is not ordered it may be 3, 4 or 5 etc...
and i wanted to get :
Array(
Array( "ID" => 1, "Name" => "name 1"),
Array( "ID" => 2, "Name" => "name 2"),
Array( "ID" => 3, "Name" => "name 3"),
Array( "ID" => 4, "Name" => "name 4"),
Array( "ID" => 5, "Name" => "name 5"),
Array( "ID" => 6, "Name" => "name 6"));
Is there an easy way to do this ?
EDIT :
Edited the above array to add :
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
which aren't nested but i still want them to be in my final array.
Thanks.
//Assuming your data is in $in
$out=array();
foreach($in as $k=>$v) {
while ((is_array($v)) && (isset($v[0]))) $v=$v[0];
//See below for next line
$out[]=$v;
}
print_r($out);
With the marked line being either $out[$k]=$v; or $out[]=$v; depending on wether you want to keep the 1st-level keys. In your desired output you do not ,so use the shown version
Edit
With you changed input array, you need to do something like
function addtoarray($inarray, &$outarray) {
foreach ($inarray as $i) {
if (!is_array($i)) continue;
if (isset($i['ID'])) $outarray[]=$i;
else addtoarray($i,$outarray);
}
}
$out=array();
addtoarray($in,$out);
print_r($out);
This was tested against your new input data
You could recurse through the array and check for the ID field.
function combine_array(array $src, array &$dest)
{
if( isset( $src['ID'] ) ) {
$dest[] = $src;
return;
}
foreach( $sub in $src ) {
combine_array( $sub, $dest );
}
}
Just wrote this off the top of my head, no testing, so it might have a few problems. But that's the basic idea.
This may work for you, assuming $array is the variable and php 5.3
//process
$array = array_map(function($block) {
$return = '';
foreach ($block as $sub) {
if (true === isset($sub['ID']) {
$return = $block;
break;
}
}
return $block;
}, $array);
array_filter($array); //remove empty elements
Wrote up a quick recursive function. You'll need to write any appropriate error handling and check the logic, since a discrepancy in your data could easily turn this into an infinite loop:
$output = array();
foreach ( $data as $d ) {
$output[] = loop_data( $d );
}
function loop_data( $data ) {
// Check if this is the right array
if( ! array_key_exists( "ID", $data ) ) {
// Go deeper
$data = loop_data( $data[0] );
}
return $data;
}

Categories