Laravel: Combine values in array - php

can I ask for your help? I have values in the array and I want to combine them to become one value. I want a result that 'gendesc' 'dmdnost' 'stredesc' 'formdesc' 'rtedesc' will be in one column. Thanks.
foreach($data as $item){
$tmp = array();
$tmp_item = (array) $item;
$tmp['description'] = $tmp_item['gendesc'];
$tmp['m1'] = $tmp_item['dmdnost'];
$tmp['m2'] = $tmp_item['stredesc'];
$tmp['m3'] = $tmp_item['formdesc'];
$tmp['m4'] = $tmp_item['rtedesc'];
$final_data [] = $tmp;
}
print_r($final_data);

Can you try
foreach($data as $item){
$tmp_item = (array) $item;
$tmp = $tmp_item['gendesc']
. ' ' . $tmp_item['dmdnost']
. ' ' . $tmp_item['stredesc']
. ' ' . $tmp_item['formdesc']
. ' ' . $tmp_item['rtedesc'];
$final_data[] = array('description' => $tmp);
}
print_r($final_data);

You want this?
foreach($data as $item){
$tmp = array();
// ver.1
$tmp['description'] = $item['gendesc']
. $item['dmdnost']
. $item['stredesc']
. $item['formdesc']
. $item['rtedesc'];
// ver.2 also you can use one-line shortcut with implode instead of ver.1
$tmp['description'] = trim(implode(" , ", $item));
$final_data[] = $tmp;
}
print_r($final_data);

Try this,
$i =0;
foreach($data as $item)
{
$tmp = [];
$tmp[$i]['description'] = $item['gendesc'];
$tmp[$i]['m1'] = $item['dmdnost'];
$tmp[$i]['m2'] = $item['stredesc'];
$tmp[$i]['m3'] = $item['formdesc'];
$tmp[$i]['m4'] = $item['rtedesc'];
$i++;
}
print_r($tmp);

Related

Returning JSON from a PHP function

I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));

i want add multiple product using php session

I want to print both
<?php
//in file A
$_SESSION['cart']['prices'] = array('1000');
$_SESSION['cart']['services'] = array('game');
//In File B
$_SESSION['cart']['prices'] = array('2000');
$_SESSION['cart']['services'] = array('game2');
//in file C
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}
?>
Better use this :
$_SESSION['cart']['prices'][] = array('1000');
$_SESSION['cart']['services'][] = array('game');
//In File B
$_SESSION['cart']['prices'][] = array('2000');
$_SESSION['cart']['services'][] = array('game2');
According to the current data foreach loop will execute two times. It will print Array as $service is array array('1000') and array('2000') same as for $_SESSION['cart']['prices'][$key]
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}
Try this :
$array1 = array('1000','2000');
$array2 = array('game1','game2');
foreach($array1 as $index=>$key)
{
$_SESSION['cart']['prices'][] = $key;
$_SESSION['cart']['services'][] = $array2[$index];
}
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}

var_export prettifier / visualizer

I'm using var_export to dump output to logs when errors occur. However since the result is in pure text, I don't get a chance to push it through some sort of library like krumo so I can interactively explores the output.
What methods do people have to deal with making var_export text more readable?
Here is my function, it works well for multidimensional arrays:
function VE($varname, $varval, $short_syntax=true, $tag = ' ', $comma='', $end_line="\r\n") {
$res = '';
if($short_syntax){
$begin_array = '[';
$end_array = ']';
} else {
$begin_array = 'array(';
$end_array = ')';
}
$arr = explode('/',$varname);
$dim =count($arr)-1;
$lastKey = end($arr);
if (! is_array($varval)){
if( is_string($varval)) $varval = "'$varval'";
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $varval . $comma . $end_line;
}else{
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $begin_array . $end_line;
$count_varval = 0;
$dim_varval = count($varval);
foreach ($varval as $key => $val){
$count_varval++;
if($count_varval<$dim_varval) $commma=','; else $commma='';
if( is_string($key)) $key = "'$key'";
$res .= VE ($varname . "/" . $key , $val, $short_syntax, $tag, $commma);
}
$res .= str_repeat($tag,$dim) . $end_array . $comma . $end_line;
}
return $res;
}
$bigarray = array(); // your array
$bb = VE ('$bigarray', $bigarray);
echo "<pre>$bb</pre>";
I hope it helps ;)

PHP foreach loop

I need to transfer the values from a PHP array into a JavaScript array so that it can be used in my application, I have managed to get up to this:
var Descriptions = array(<?php
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
echo $ID . "[" . $description . "]" . ",";
}
?>);
and it works fine except for one thing: I dont know how to tell PHP to not put a comma after the last array value. The extra comma is causing a syntax error so it breaks my code.
Thanks in advance for any ideas,
RayQuang
The quick and dirty way:
for($i = 0, $c = count($tasks); $i < $c; $i++) {
$task = $tasks[$i];
...
echo $ID . "[" . $description . "]" . (($i != $c-1) ? "," : '');
}
There are obviously other ways of accomplishing this, one way would be to build up a string and then use the trim() function:
$tasks_str = '';
foreach(...) {
...
$tasks_str .= ...
}
echo trim($tasks_str, ',');
Or, (my favorite), you could build up an array and then use implode on it:
$tasks_array = array();
foreach(...) {
...
$tasks_array[] = ...
}
echo implode(',', $tasks_array);
don't try to build it manually, use json_encode
var Descriptions = <?=json_encode($tasks);?>;
var DescriptionsString = <?php
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
echo $ID . "[" . $description . "]" . ",";
}
?>;
var Descriptions = DescriptionsString.split(',');
try,
var Descriptions = array(<?php
$str = '';
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
$str .= $ID . "[" . $description . "]" . ",";
}
echo trim($str,',');
?>);
Not one to miss out on a trend:
$out = array();
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
$out[] = $ID . "[" . $description . "]";
}
echo implode(',', $out);
Using implode().

PHP Dynamic Breadcrumb

I got this code from someone and it works very well, I just want to remove the link from the last element of the array:
//get rid of empty parts
$crumbs = array_filter($crumbs);
$result = array();
$path = '';
foreach($crumbs as $crumb){
$path .= '/' . $crumb;
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumb));
$result[] = "$name";
}
print implode(' > ', $result);
This will output for example:
Content > Common > File
I just want a to remove the link from the last item - "File" to be just plain text..
I tried myself to count the array items and then if the array item is the last one then to print as plain text the last item.. but I'm still noob, I haven't managed to get a proper result..
Thank you!
This should work:
$crumbs = array_filter($crumbs);
$result = array(); $path = '';
//might need to subtract one from the count...
$count = count($crumbs);
foreach($crumbs as $k=>$crumb){
$path .= '/' . $crumb;
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumb));
if($k != $count){
$result[] = "$name";
} else {
$result[] = $name;
}
}
print implode(' > ', $result);
You could simply tweak your existing code to use a 'normal' loop (rather than a foreach iterator) to achieve this.
For example:
//get rid of empty parts
$crumbs = array_filter($crumbs);
$result = array();
$path = '';
$crumbCount = count($crumbs);
for($crumbLoop=0; $crumbLoop<$crumbCount; $crumbLoop++) {
$path .= '/' . $crumbs[$crumbLoop];
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumbs[$crumbLoop]));
$result[] = ($crumbLoop != $crumbCount -1) ? "$name" : $name;
}
print implode(' > ', $result);
N.B: I don't have access to PHP at the moment, so the above might not be error free, but you should get the idea.
for($i=0;$i< sizeof($crumbs);$i++) {
$path .= '/' . $crumbs[$i];
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumbs[$i]));
if ($i != sizeof($crumbs)-1) {
$result[] = "$name";
}else {
$result[] = $name;
}
}

Categories