How to loop trought array and create array from common values? - php

i need to filter an array and spilt them into different arrays. Here the actual working and slow code:
-----> http://viper-7.com/GVRbVp
but that method is still slow, i think. At least 3 loops...
i would like to scan one time only the array and create array on the fly, i tried with this:
$stray = json_decode('[{"id":"1","zona":"Pescara"},{"id":"2","zona":"Pescara"},{"id":"3","zona":"Teramo"},{"id":"4","zona":"Pescara"},{"id":"5","zona":"Pescara"},{"id":"6","zona":"Teramo"},{"id":"7","zona":"Pescara"},{"id":"8","zona":"Pescara"},{"id":"9","zona":"Pescara"},{"id":"10","zona":"Pescara"},{"id":"11","zona":"Pescara"},{"id":"12","zona":"Pescara"},{"id":"13","zona":"Teramo"},{"id":"14","zona":"Chieti"},{"id":"15","zona":"Chieti"},{"id":"16","zona":"Aquila"},{"id":"17","zona":"Chieti"},{"id":"18","zona":"Chieti"},{"id":"19","zona":"Chieti"},{"id":"20","zona":"Chieti"},{"id":"21","zona":"Campobasso"},{"id":"22","zona":"Aquila"},{"id":"23","zona":"Pescara"},{"id":"24","zona":"Pescara"},{"id":"25","zona":"Pescara"},{"id":"26","zona":"Pescara"},{"id":"27","zona":"Chieti"},{"id":"28","zona":"Pescara"},{"id":"29","zona":"Pescara"},{"id":"30","zona":"Chieti"},{"id":"31","zona":"Pescara"},{"id":"32","zona":"Chieti"},{"id":"33","zona":"Teramo"},{"id":"34","zona":"Teramo"},{"id":"35","zona":"Teramo"},{"id":"37","zona":"Teramo"},{"id":"39","zona":"Pescara"}]',true);
$all_cat = array();
foreach($stray as $row) {
$item_cat = $row['zona'];
if($$cat) { /* check if the category array exist */
$cat = array(); /* if not, create array */
if( !in_array($item_cat,$$item_cat) ) { /* and add the value */
array_push($$item_cat,$row);
}
array_push($all_cat, $cat); /* add new category to index of categories */
} else {
if( !in_array($item_cat,$$item_cat) ) { /* Otherwise just add the value */
array_push($$item_cat,$row);
}
}
}
echo '<pre>'.print_r($cat,true).'</pre>';

If I understand correctly, you could simplify it to
foreach($stray as $row) {
if(!isset($$row['zona'])) {
$$row['zona']=array();
}
${$row['zona']}[] = $row;
}
so now your viper-7 would look like
$stray = json_decode(...[removed to simplify]...,true);
foreach($stray as $row) {
if(!isset($$row['zona'])) {
$$row['zona']=array();
}
${$row['zona']}[] = $row;
}
echo 'Pescara :<pre style="max-height: 50px; overflow: auto">'.print_r($Pescara,true).'</pre>';
echo 'Teramo :<pre style="max-height: 50px; overflow: auto">'.print_r($Teramo,true).'</pre>';
echo 'Chieti :<pre style="max-height: 50px; overflow: auto">'.print_r($Chieti,true).'</pre>';
echo 'Aquila :<pre style="max-height: 50px; overflow: auto">'.print_r($Aquila,true).'</pre>';
echo 'Campobasso :<pre style="max-height: 50px; overflow: auto">'.print_r($Campobasso,true).'</pre>';

For loop through the array. For every element do if else checking for all 3 "zona". If it matches one push it to the respective array within the if and move on to the next element in the array.

Related

add CSS with array of variables in head - Wordpress - PHP

I'm trying to return css build with multiple variables in my Wordpress website, its kind of working but it's only returning the first array. If i echo instead of return inside the foreach it shows the code correctly but outside the correct location.
Sorry for the bad code and possible definitions about php. I have only just started to learn php.
The code
function child_custom_color_css4() {
function child_custom_color_css2() {
function test_loop_1_beta() {
$boo = 'soortverhaal0 ';
$foo = 'soortverhaal1 ';
return array($boo, $foo);
}
$loops = test_loop_1_beta();
global $nectar_options;
$Styled=array();
foreach ($loops as $loop) {
return '
#test-loop.'. $loop .' {
background-color: '.esc_attr($nectar_options["accent-color"]).' !important;
}
';
}
return implode($Styled);
}
$get_arrays = child_custom_color_css2();
wp_add_inline_style( 'main-styles', $get_arrays);
}
add_action('wp_enqueue_scripts','child_custom_color_css4', 20); '''
Output:
<style id="main-styles-inline-css" type="text/css">
#test-loop.soortverhaal0 {
background-color: #f04e23 !important;
}
</style>
Edit: what need:
<style id="main-styles-inline-css" type="text/css">
#test-loop.soortverhaal0 {
background-color: #f04e23 !important;
}
#test-loop.soortverhaal1 {
background-color: #f04e23 !important;
}
</style>
I think you could do something like that:
function child_custom_color_css4() {
function child_custom_color_css2() {
$loops = [
'soortverhaal0 ',
'soortverhaal0 ',
];
global $nectar_options;
$styled = [];
foreach ($loops as $loop) {
$styled[] = '#test-loop.' . $loop . ' { background-color: ' . esc_attr( $nectar_options['accent-color'] ) . ' !important; }';
};
return implode("\n",$styled);
}
$get_arrays = child_custom_color_css2();
wp_add_inline_style( 'main-styles', $get_arrays);
}
add_action('wp_enqueue_scripts','child_custom_color_css4', 20);
I do an array push to acumulate each loop into $style array.
I think you would need to define other separator for the implode function like:
return implode("\n",$styled)

php regex select less code

I want to select all less code from a file .But i can not find the right way to do it.
This is my code so far
$d = <<<EOT
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
}
}
EOT;
$pattern = '/.*\{(?s:.*?)\}$/mi';
$t = preg_match_all($pattern, $d, $out, PREG_PATTERN_ORDER);
foreach ($out[0] as $key) {
echo '<br><pre>'.$key."</pre>";
}
And this is the result:
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
For the first 2 classes is ok but last one is not ok because they are missing 2 other }.
How can i fix it?
It looks like you want to match individual blocks, so a recursive pattern will return balanced braces. As stated in comments under the question, this method may break when character anomalies occur. I believe there are css parsers out "in the wild" but I don't have any to recommend.
Code: (Demo)
if (preg_match_all('~.*\{((?R)|[^}])*}~', $d, $out)) {
echo implode("\n---\n",$out[0]);
}
Output:
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
---
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
---
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
}
}
If you don't need to separate the blocks, you can modify the pattern like this:
~[^{]*\{((?R)|[^}])*}~
But then it depends on what your actual input.

Fix illegal string offset PHP

CODE
Foreach Loop
foreach ($LS::getBase() as $base) {
$fromDatabaseThumb = $base['base-thumbnail'];
$fromDatabaseDescription = $base['base-description'];
$fromDatabaseTitle = $base['base-title'];
echo "
<div style='background-color: #ffffff; width: 725px; height: 280px; display: inline-block; position: relative;''>
<div style='display: inline-block; max-width: 450px; max-height: 260px; margin: 12px; float: left;' class='baseThumb'>
<img src='$fromDatabaseThumb' style='max-width: 450px; max-height: 260px'>
</div>
<div class='baseInfo' style='display: inline-block; width: 250px; height: 253px; margin-top: 12px;'>
<h3 style='margin: 0; font-family: helvetica; max-width: 250px; max-height: 22px; overflow: hidden;'>$fromDatabaseTitle</h3>
<p style='margin-top: 8px; word-wrap: break-word;'>
<strong>Description:</strong><br>
" . $fromDatabaseDescription . "
</p>
</div>
</div>
";
}
getBase() function
public static function getBase($what = '*') {
self::construct();
if( is_array($what) ){
$columns = implode("`,`", $what);
$columns = "`{$columns}`";
}else{
$columns = $what != "*" ? "`$what`" : "*";
}
$sql = self::$dbh->prepare("SELECT {$columns} FROM baselayouts");
$sql->execute();
$data = $sql->fetch(\PDO::FETCH_ASSOC);
if( !is_array($what) ){
$data = $what == "*" ? $data : $data[$what];
}
return $data;
}
The ERROR:
WHAT I DID
I have done research and couldn't find anything that worked. So I tinkered around my code a bit and still couldn't fix it.
EXTRA INFO
I did a var_dump() since I saw in other posts that was facing the same problem as I am did a var_dump() so I thought I would do it just in case that would help you guys in any way.
var_dump()
array(4) {
["id"]=> string(1) "1"
["base-title"]=> string(14) "Base Layout #1"
["base-thumbnail"]=> string(24) "/res/img/baseLayout1.png"
["base-description"]=> string(73) "This is the base test description. Hopefully it does what it needs to do."
}
A foreach loop like that doesn't call the method on each iteration. It is called once on the first loop and then each later iteration loops over that returned value. So calling getBase is returning one row from the query and then you are loop over each column from that result making $base inside the loop the value in that column, not the array of the row. The var_dump appears to be return return from getBase, but not $base inside the loop. If you did a var_dump($base); in the loop you would see each string once. To fix it, you likely want to change your getBase to call PDOStatement::fetchAll which will return a 2d array like $result[rowNum][colName].
Edit: Also, switching the loop to another structure like a while loop that would evaluate the full statement on each iteration would put you into an infinite loop as each time you call getBase you would re-query, return the first row and repeat.

How to design the data that you gathered from the table

I've printed all the data from the database, but my main problem is how to design my data.
I have a table named post_tbl and columns(post_id,post_message,post_date)
this is my query:
$query = "SELECT `post_id`,`post_message` FROM `post_tbl` ORDER BY `post_date`;
This is how I print in php:
if($query_run = mysql_query($query))
{
while($query_row = mysql_fetch_assoc($query_run))
{
$ex_post_id = $query_row['post_id'];
$ex_post_message = $query_row['user_name'];
$ex_post_date= $query_row['post_date'];
echo $ex_post_message;
}
}
how do I make my ex_post_message have a unfirom border and width using html and css? pls help. thanks
if($query_run = mysql_query($query))
{
while($query_row = mysql_fetch_assoc($query_run))
{
$arrMaster[] = $ex_post_message;
}
}
foreach ($arrMaster as $key => $value)
{
if($i==0)
{
$table1.="<tr>";
foreach ($value as $keyc => $valuec)
{
$table1.="<th>".$keyc."</th>";
}
$table1.="</tr>";
$i=1;
}
$table1.="<tr>";
foreach ($value as $keyc => $valuec)
{
$table1.="<td>".$valuec."</td>";
}
$table1.="</tr>";
}
$table1 .= "</table>";
echo $table1;
at this way you can add any style to your table or any class
Yes you can echo HTML element like:
echo "<div class='classname1'>" . $ex_post_message . "</div>";
Then the class classname1 should handle the design. Like the following:
<style>
.classname1{
width: 100px;
height: 30px;
border: 1px solid blackl
}
</style>
There are many ways to achieve this. The one that I've provided is just an example.

Make var_dump look pretty [duplicate]

This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
I have a simple $_GET[] query var set for showing testing data when pulling down queries from the DB.
<?php if($_GET['test']): ?>
<div id="test" style="padding: 24px; background: #fff; text-align: center;">
<table>
<tr style="font-weight: bold;"><td>MLS</td></tr>
<tr><td><?php echo KEY; ?></td></tr>
<tr style="font-weight: bold;"><td>QUERY</td></tr>
<tr><td><?php echo $data_q; ?></td></tr>
<tr style="font-weight: bold;"><td>DATA</td></tr>
<tr><td><?php var_dump($data); ?></td></tr>
</table>
</div>
<?php endif; ?>
When I do var_dump, as expected it's this big array string that is all smushed together. Is there a way to add in line breaks at least for this or display the var_dump in a way that's more readable? I'm open to jQuery suggestions on manipulating the string after it's posted.
I really love var_export(). If you like copy/paste-able code, try:
echo '<pre>' . var_export($data, true) . '</pre>';
Or even something like this for color syntax highlighting:
highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");
Reusable function:
function highlight_array($array, $name = 'var') {
highlight_string("<?php\n\$$name =\n" . var_export($array, true) . ";\n?>");
}
You can do the same with print_r(). For var_dump() you would just need to add the <pre> tags:
echo '<pre>';
var_dump($data);
echo '</pre>';
Try xdebug extension for php.
Example:
<?php var_dump($_SERVER); ?>
Outputs:
Use preformatted HTML element
echo '<pre>';
var_dump($data);
echo '</pre>';
I have make an addition to #AbraCadaver answers.
I have included a javascript script which will delete php starting and closing tag.
We will have clean more pretty dump.
May be somebody like this too.
function dd($data){
highlight_string("<?php\n " . var_export($data, true) . "?>");
echo '<script>document.getElementsByTagName("code")[0].getElementsByTagName("span")[1].remove() ;document.getElementsByTagName("code")[0].getElementsByTagName("span")[document.getElementsByTagName("code")[0].getElementsByTagName("span").length - 1].remove() ; </script>';
die();
}
Result before:
Result After:
Now we don't have php starting and closing tag
I don't seem to have enough rep to close this as a duplicate, but it is one if someone else can do that. I posted the same thing over at A more pretty/informative Var_dump alternative in PHP? but for the sake of saving time, I'll copy/paste it here too:
I had to add another answer here because I didn't really want to go through the steps in the other solutions. It is extremely simple and requires no extensions, includes etc and is what I prefer. It's very easy and very fast.
First just json_encode the variable in question:
echo json_encode($theResult);
Copy the result you get into the JSON Editor at http://jsoneditoronline.org/ just copy it into the left side pane, click Copy > and it pretty prints the JSON in a really nice tree format.
To each their own, but hopefully this helps some others have one more nice option! :)
Here's an alternative, actively maintained open source var_dump on steroids:
https://github.com/php-sage/sage
It works with zero set up and is more useable than Xdebug's var_dump and symfony/var-dumper.
Example which bypasses the dumped object size limit on the fly with Kint:
require 'sage.phar';
+d( $variable ); // append `+` to the dump call
Here's a screenshot:
If it's "all smushed together" you can often give the ol' "view source code" a try. Sometimes the dumps, messages and exceptions seem like they're just one long string when it turns out that the line breaks simply don't show. Especially XML trees.
Alternatively, I've once created a small little tool called InteractiveVarDump for this very purpose. It certainly has its limits but it can also be very convenient sometimes. Even though it was designed with PHP 5 in mind.
The best what and easiest way to get nice var_dump is use xDebug (must have for any php dev)
Debian way install
In console: apt-get install php-xdebug
after that you should open php.ini (depends on which stack you use) for it's /etc/php/7.0/fpm/php.ini
Search for display_errors
set same -> display_errors = On
Check html_errors in same file a little bit below, it's also must be On
Save and exit
After open /etc/php/7.0/fpm/conf.d/20-xdebug.ini
And add to the end:
```
xdebug.cli_color=1
```
Save and exit.
A lot other available option and documentation for xdebug can be founded here.
https://xdebug.org/docs/
Good luck and Have Fun !!!
Result
You could use this one debugVar() instead of var_dump()
Check out: https://github.com/E1NSER/php-debug-function
Here is my function to have a pretty var_dump. Combined with Xdebug, it helps a lot to have a better view of what we are dumping.
I improved a bit the display of Xdebug (give some space around, separator between values, wrap long variables, etc).
When you call the function, you can set a title, a background, a text color to distinguish all your var_dump in a page.
Or not ;)
/**
* Pretty var_dump
* Possibility to set a title, a background-color and a text color
*/
function dump($data, $title="", $background="#EEEEEE", $color="#000000"){
//=== Style
echo "
<style>
/* Styling pre tag */
pre {
padding:10px 20px;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
/* ===========================
== To use with XDEBUG
=========================== */
/* Source file */
pre small:nth-child(1) {
font-weight: bold;
font-size: 14px;
color: #CC0000;
}
pre small:nth-child(1)::after {
content: '';
position: relative;
width: 100%;
height: 20px;
left: 0;
display: block;
clear: both;
}
/* Separator */
pre i::after{
content: '';
position: relative;
width: 100%;
height: 15px;
left: 0;
display: block;
clear: both;
border-bottom: 1px solid grey;
}
</style>
";
//=== Content
echo "<pre style='background:$background; color:$color; padding:10px 20px; border:2px inset $color'>";
echo "<h2>$title</h2>";
var_dump($data);
echo "</pre>";
}
function var_view($var)
{
ini_set("highlight.keyword", "#a50000; font-weight: bolder");
ini_set("highlight.string", "#5825b6; font-weight: lighter; ");
ob_start();
highlight_string("<?php\n" . var_export($var, true) . "?>");
$highlighted_output = ob_get_clean();
$highlighted_output = str_replace( ["<?php","?>"] , '', $highlighted_output );
echo $highlighted_output;
die();
}
There is a Symfony package for this: https://symfony.com/doc/current/components/var_dumper.html.
Here is a function I made for showing arrays in a nice way:
function nicevar($var,$title=''){
if(is_array($var)){
$table = '<table>';
if($title){
$table .= '<tr><th colspan="20">'.$title.'</th></tr>';
}
foreach($var as $k => $v){
$table .= '<tr>';
$table .= '<td><b>'.$k.'</b></td>';
$table .= '<td>';
if(is_array($v)){
$table .= nicevar($v);
}else{
$table .= $v;
}
$table .= '</td>';
$table .= '</tr>';
}
$table .= '</table>';
}else{
$table = $var;
}
return $table;
}
usage:
echo nicevar($_SESSION['debug'],'Structure of debug');
use this styling to make it nice:
<style>
body {
padding: 30px;
}
table {
margin: 5px;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th {
background-color: #9fff96;
}
th, td {
padding: 2px;
border-spacing: 2px;
}
</style>
in CI4, it's simpler to make the output prettier:
dd($this->request);
here is the result
I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.
<?php
function debug_display($var,$show = false) {
if($show) { $dis = 'block'; }else { $dis = 'none'; }
ob_start();
echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
<pre>';
if(is_bool($var)) {
echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
}else {
if(FALSE == empty($var) && $var !== NULL && $var != '0') {
if(is_array($var)) {
echo "Number of Indexes: " . count($var) . "\n";
print_r($var);
} elseif(is_object($var)) {
print_r($var);
} elseif(#is_file($var)){
$stat = stat($var);
$perm = substr(sprintf('%o',$stat['mode']), -4);
$accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
$modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
$change = gmdate('Y/m/d H:i:s', $stat['ctime']);
echo "
file path : $var
file size : {$stat['size']} Byte
device number : {$stat['dev']}
permission : {$perm}
last access time was : {$accesstime}
last modified time was : {$modification}
last change time was : {$change}
";
}elseif(is_string($var)) {
print_r(htmlentities(str_replace("\t", ' ', $var)));
} else {
print_r($var);
}
}else {
echo 'Undefined';
}
}
echo '</pre>
</div>';
$output = ob_get_contents();
ob_end_clean();
echo $output;
unset($output);
}
Use
echo nl2br(var_dump());
This should work ^^

Categories