I'm making a json string which only contains the values which are entered in the form. so far it's going good but the only problem is that the foreach function which makes the string does not take all items from array.
Let's explain something and show my code:
if the $title is not empty I want my final ($content1) string to start with that value. Because it has some other quotes and curlybraces than other values. the same with the date field I also made an if for that because it also contains "date" in it. See my code below:
$title = "fiat titel";
$engine = "1.8";
$day = "1";
$month = "2";
$year = "1999";
$dateBuild = "02/02/1999";
// assoc array push function
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
$array = array();
if(!empty($title)) {
$array = array_push_assoc($array, 'title', $title);
}
if(!empty($color)) {
$array = array_push_assoc($array, 'field_modelcolor', $color);
}
if(!empty($model)) {
$array = array_push_assoc($array, 'field_carmodel', $model);
}
if(!empty($engine)) {
$array = array_push_assoc($array, 'field_modelengine', $engine);
}
if(!empty($fuel)) {
$array = array_push_assoc($array, 'field_modelfuel', $fuel);
}
if(!empty($day) && !empty($month) && !empty($year)) {
$array = array_push_assoc($array, 'field_modelyear', $dateBuild);
}
$content1 = "";
foreach($array as $ftitle => $value) {
if(empty($content1) && !empty($title)) {
$content1 = ',"' . $ftitle . '":"' . $value . '"';
}
if(!empty($day) && !empty($month) && !empty($year)) {
$content1 = ',"' . $ftitle . '":{"und":[{"value":{"date":"' . $value . '"}}]}';
}
$content1 = ',"' . $ftitle . '":{"und"[{"value":"' . $value . '"}]}';
}
$postContent = '{"type":"carmodels"' . $content1 . '}';
var_dump($array);
echo $postContent;
Right now it's only echo'ing:
{"type":"carmodels","field_modelyear":{"und"[{"value":"02/02/1999"}]}}
And it should be (example):
{"type":"carmodels","field_modelyear":{"und":[{"value":{"date":"02/02/1999"}}]},"field_modelengine":{"und"[{"value":"1.6"}]}}
Thanks in advance!
Related
public function getChildren($parent, $level=0,$getlevel=array()) {
$criteria = new CDbCriteria;
$criteria->condition='referred_by_user_id=:id';
$criteria->params=array(':id'=>$parent);
$count = array(0=>0);
$model = $this->findAll($criteria);
// $levelcount = array();
$user=User::model()->findbypk(Yii::app()->user->id);
if($user->level!=$level)
{
foreach ($model as $key) {
$count[0]++;
$index=1;
// echo str_repeat(' — ', $level) . $key->name . "<br />";
$children= $this->getChildren($key->id, $level+1);
// pr($children);die;
foreach ($children as $child)
{
// pr($child);
if ($child==0)
continue;
if (isset($count[$index]))
$count[$index] += $child;
else
$count[$index] = $child;
$index++;
}
}
}
return $count;
}
I can output only the number of users. How do I get the user id for each level in an array?
I think the problem is you must make $index variable outside of for
I made something similiar a while ago:
public static function getChildren($idParent) {
$elem = [];
$childrens = Arbol::model()->findAll("estado = 1 and id_parent = " . $idParent . ' ORDER BY level');
foreach ($childrens as $key => $child) {
$persona = Persona::model()->findbyPk($child->id_child);
if ((int) $persona->id_superior === $idParent) {
$nombre = explode(" ", $persona->nombres);
$elem[$key] = [
"id" => $persona->id_persona,
"image" => Yii::app()->baseUrl . '/images/user-icon' . ($persona->pago_inscripcion ? '-activo.png' : '.png'),
"text" => [
'title' => $nombre[0] . ' ' . substr($persona->apellido_paterno, 0, 1) . '.'
]
];
} else {
$keySUperior = array_search($persona->id_superior, array_column($elem, "id"));
if (is_int($keySUperior)) {
$elem[$keySUperior]["children"] = self::getChildren((int) $persona->id_superior);
}
}
}
return $elem;
}
I hope i give you any help
I have a situation showed in the PHP code below, and I want to make a recursive function called check_recursive().
I have made the check_recursive() function below, but I want a recursive function, if it is possible.
Thank You!
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = $this->check_recursive($old_menu);
function check_recursive($old_menu)
{
$i = 0;
$new_menu = [];
foreach ($old_menu as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$e = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$y = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$a = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['children'][$a]['id'] = $menu_item['id'] . '|' . $name;
}
$a++;
}
}
}
$y++;
}
}
}
$e++;
}
}
}
$i++;
}
return $new_menu;
}
function check_menu($string){
//Check if string exists in database
if($string){
return 'String exists';
}
return false;
}
I came up with this :
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = check_recursive($old_menu);
function check_recursive($old_menu)
{
$new_menu = array();
foreach ($old_menu as $item) {
$name = check_menu($item['id']);
if($name){
$new_item = array(
'id' => $item['id'] . '|' . $name,
);
if(isset($item['children'])){
$new_item['children'] = check_recursive($item['children']);
}
$new_menu[] = $new_item;
}
}
return $new_menu;
}
function check_menu($string)
{
//Check if string exists in database
if ($string) {
return 'String exists';
}
return false;
}
Let me know if it suits your needs.
I'm looking for an easy solution to create a little function to merge two arrays with value concat (I'm using it to create html tag attribute):
$default["class"] = "red";
$new["class"] = "green";
$new["style"] = "display:block"
The result:
$res["class"] = "red green";
$res["style"] = "display: block";
and one more option:
if the $new is not an array, just concat with the $default["class"] (if this exist), and the other side: if the $default is a simple string, convert to array: $default["class"] = $default;
I created a function but would like to use an easier, shorter way for that:
function attrMerge( $default, $new="" ){
$res = array();
if(!is_array($default)) {
$res["class"] = $default;
}
else {
$res = $default;
}
if( $new !== "" ){
if(!is_array($new)) {
if(isset($res["class"])){
$res["class"].= " ".$new;
}
}
else {
foreach($new as $key=>$value) {
if( isset($res[$key]) ) {
$res[$key].= " ".$value;
}
else {
$res[$key] = $value;
}
}
}
}
return $res;
}
$a = attrMerge("red", array("class"=>"green", "style"=>"display: block;"));
I think this is the function that you need. I have initialised the css classes and styles as empty and in depends what you pass into the function then you get the relevant array
/**
* This function returns an array of classes and styles
*
* #param $default
* #param $new
* #return array
*/
function attrMerge($default=null, $new=nul)
{
$result = array();
$result['class'] = "";
$result['style'] = "";
// add default class if exists
if (!empty($default) && is_string($default)) {
// $default is string
$result['class'] = $default;
}
if (!empty($default)
&& is_array($default)
) {
if (array_key_exists('class', $default)
&& !empty($default['class'])
) {
// $default['class'] exists and it's not empty
$result['class'] = $default['class'];
}
if (array_key_exists('style', $default)
&& !empty($default['style'])
) {
// $default['style'] exists and it's not empty
$result['style'] = $default['style'];
}
}
// add additional classes OR styles
if (!empty($new)) {
if(!is_array($new)) {
$result['class'] = empty($result['class'])
? $new
: $result['class'] . " " . $new;
} else {
foreach ($new as $key => $value) {
if (isset($result[$key])) {
$result[$key] = empty($result[$key])
? $value
: $result[$key] . " " . $value;
} else {
$result[$key] = $value;
}
}
}
}
return $result;
}
A way I believe suits your need, hopefully it's as adaptable and effecient as you were expecting.
$array1 = array(
'class' => 'class1',
'style' => 'display: none;'
);
$array2 = array(
'class' => 'class2'
);
$arrayFinal = arrayMerge($array1, $array2);
var_dump($arrayFinal);
function arrayMerge($arr1, $arr2 = ''){
// Array of attributes to be concatenated //
$attrs = array('class');
if(is_array($arr2)){
foreach($attrs as $attr){
if(isset($arr1[$attr]) && isset($arr2[$attr])){
// Not using .= to allow for smart trim (meaning empty check etc isn't needed //
$arr1[$attr] = trim($arr1[$attr] . ' ' . $arr2[$attr]);
}
}
}else{
$arr1['class'] = trim($arr1['class'] . ' ' . $arr2);
}
return $arr1;
}
$def = ['class' => 'red'];
$new = ['class' => 'green', 'style' => 'style'];
function to_array($in) {
return is_array($in) ? $in : ['class' => $in];
}
$def = to_array($def);
$new = to_array($new);
$res = $def;
array_walk($new, function ($val, $key) use (&$res) {
$res[$key] = trim(#$res[$key] . ' ' . $val);
});
var_dump($res);
I am having a real issue with variable interpolation - maybe what I'm trying to do shouldn't be done? Sample code (IRL, the array is 70+ elements):
<form submit>
$_POST['A']; //returns 12
$_POST['B']; //returns 8
<query to get orig field values>
$OrigA = $row->appA; //returns 12
$OrigB = $row->appB; //return 14
<array of names>
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$new = "\$_POST['app" . $field . "']";
$fieldname = "app" . $field;
if (${$orig} != ${$new}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
The part if (${$orig} != ${$new}) is what's not working as I would expect. When I print it out to screen with print "DEBUG: if (${$orig} != ${$new}) { $querystr .= \"('default', $applID, '$fieldname', '{$orig}', '{$new}', '$DateTimeReq', '$hvid')\"; };<br />\n";, I see my variables aren't interpolating properly, my debug print says: DEBUG: if ( != ) { .... It should interpolate to (for B): DEBUG: if (8 != 14) { ...
I have tried various combinations of dollar signs and braces, but I don't seem to be making headway. Am I barking up the wrong tree here?
Thanks as always!!
Like this : No interpolation POST variable
<?php
$A = $_POST['A'] = 12; //returns 12
$B = $_POST['B'] = 8; //returns 8
$OrigA = 12; //returns 12
$OrigB = 14; //return 14
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$fieldname = "app" . $field;
if (${$orig} != ${$field}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
?>
See http://codepad.org/Ecro0PyG
I don't get all your questions but maybe this code could help you a little (you can use your $_POST var instead of mine $post, that is just to show result and debug):
$post = array();
$post['A'] = 12;
$post['B'] = 8;
$OrigA = 12;
$OrigB = 14;
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$origVarName = 'Orig'.$field;
echo '$$origVarName = '.$$origVarName.'<br/>';
echo '$post[$field] = '.$post[$field].'<br/>';
$fieldname = "app" . $field;
if ($$origVarName != $post[$field]) {
echo $field.' NOT EQUAL!';
} else {
echo $field.' EQUAL!';
}
}
I have a multidimensional array like this:
$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';
And another array like:
$array2['second-first']='newvalue21';
$array2['second-third-first']='newvalue231';
And I can't get the way to walk $array1 recursively to check, in each iteration, if exist any element in $array2 with a key equivalent to the current element key and their parents converted to string.
To simplify the question, I will have enough with a function that prints something like:
// walking $array1:
first
second-first
second-second
second-third-first
second-fourth
third
Thank you.
Solution based on Clément Malet answer
function print_array_reccur ($array1, $array2, $str = '')
{
foreach ($array1 as $key => $val) {
if (is_array($val)) {
if ($str == '') {
print_array_reccur($val, $array2, $key);
} else {
print_array_reccur($val, $array2, $str . '-' . $key);
}
} else {
if ($str == '') {
$result = $key;
} else {
$result = $str . '-' . $key;
}
if(isset($array2[$result]))
{
echo 'Found $array2['.$result.'] = ' . $array2[$result] . "\n";
}
}
}
}
print_array_reccur ($array1, $array2);
/* OUTPUT:
Found $array2[second-first] = newvalue21
Found $array2[second-third-first] = newvalue231
*/
I really didn't understand what you wanted in the very end, and what you want to achieve later on with your second array.
But since you are looking for a way to print something (glad you simplified that way), here it is :
$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';
function print_array_reccur ($array, $str = '') {
foreach ($array as $key => $val) {
if (is_array($val)) {
if ($str == '') {
print_array_reccur($val, $key);
} else {
print_array_reccur($val, $str . '-' . $key);
}
} else {
if ($str == '') {
echo $key . "\n";
} else {
echo $str . '-' . $key . "\n";
}
}
}
}
print_array_reccur ($array1);
Output :
first
second-first
second-second
second-third-first
second-fourth
third