Using for loop to create JSON object in PHP - php

I am trying to create a JSON object like this:
"results": [
{"key":"1","trackname":"graham#insideoutrenovations.com.au"},
{"key":"1","trackname":"sjwindsor#westnet.com.au"},
]
However my PHP code is creating a new object for each iteration, the json looks like this:
0: "{"key":"1","trackname":"graham#insideoutrenovations.com.au"}"
1: "{"key":"1","trackname":"sjwindsor#westnet.com.au"}"
Here is my php:
$results = array();
function json_response($trackName) {
return json_encode(array(
'key' => '1',
'trackname' => $trackName
));
}
//There is 3 reg expressions for each primary array so we need to iterate by 3, otherwise we will get 3 lots of the same email address
for ($i = 0; $i < $numMatches; $i = $i + $patternNum) {
$results[] = json_response($matches[0][$i]);
}
//$results = call_user_func_array('array_merge',$results);
echo json_encode($results);

you need to remove the first json_encode function
you can either try to create associative array or use function compact, that will do the work for you.
//There is 3 reg expressions for each primary array so we need to iterate by 3, otherwise we will get 3 lots of the same email address
for ($i = 0; $i < $numMatches; $i = $i + $patternNum) {
$results[] = $matches[0][$i]; // json_encode removed
}
echo json_encode(array('results' => $results));
// or
echo json_encode(compact('results'));

In final echo you encode in json an array already encoded.
Remove json_encode from json_response function.

Related

I want to know the correct syntax of declaring multiple variables in php with small changes like mentioned below

$str='abcde';//for sub-question numbers
for ($i=1; $i <=10 ; $i++) {//i loop is for question numbers 1 to 10
for ($j=0; $j<5 ; $j++) {//j loop is for sub-questions from a to e
$q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
}
}
Here the main idea is to create 50 variables from q1a,q1b,... till q10d,q10e.
I'm not 100% clear on what the values of those variables will be, but here is how to create an array with those variable names in them.
$questions = array(1,2,3,4,5,6,7,8,9,10); //questions
$subQuestions = array('a','b','c','d','e'); //sub-question
$allQuestions = array();
foreach($questions as $question) {//loop the questions
foreach($subQuestions as $subQ) {//loop the sub questions
// I'm not clear what you're trying to do here -> $q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
$allQuestions["q" . $question . $subQ] = "I'm an empty value right now"; //what value goes here?
}
}
var_dump($allQuestions);
You can do something like this
$values = array("q1a", "q1b", "q1c", "q1d", "q1e", "q2a", "q2b", "q2c", "q2d", "q2e");
for($i=;$i<$sizeof($values);$i++)
{
$values[$i] = $_POST['q{$i}{$str[j]}'];
}
If all your POST vars which you want to grab are prepended with q then just filter them with array_filter().
Then you can use extract(), but tbh, you should just use the array.
<?php
$_POST = [
'q1' => 'baz',
'foo' => 'bar',
];
$q = array_filter($_POST, function($k) {
return substr($k, 0, 1) === 'q';
}, ARRAY_FILTER_USE_KEY);
extract($q);
// filtered array
print_r($q);
// extract'ed
echo $q1;
Result:
Array
(
[q1] => baz
)
baz
https://3v4l.org/rvMR6

php, total count of a key with multi value inside a foreach (for) loop

From an REST api, I convert the json data to array data by using
$return= json_decode($response, true);
There are 2 values for the same key inside each array, example:
['some1']=>array(
[0]=> array(['data']=>0)
[1]=> array(['data']=>1)
)
..
I did a for-loop to display the value of ['data'] in which the result are 0 or 1. Now I want to count the total 0 or 1 for ['data'] inside the whole array. How can I do that?
This is my for-loop looks like:
for ($i = 0; $i < count($return['some1']); $i++){
echo $return['some1'][$i]['data'] ."<br/>" ;}
echo shows:
0
1
Thanks,
Simply extract the data column and count the values. The key will contain the value (0 or 1) and the value will contain the count:
$counts = array_count_values(array_column($return['some1'], 'data'));
echo $counts[0]; // return the count of 0s
echo $counts[1]; // return the count of 1s
If you had 2s in there then $counts[2] would contain a count of them etc...
$count_0 = 0;
$count_1 = 0;
for ($i = 0; $i < count($return['some1']); $i++){
if ($return['some1'][$i]['data'] == 0) {
$count_0++;
}
if ($return['some1'][$i]['data'] == 1) {
$count_1++;
}
}
echo $count_0;
echo '<br/>';
echo $count_1;
If you want to know how many times each value of 'data' is repeated you can use something like below to keep track:
// Your input data
$data = array(
'some1' => array(
array('data' => 0),
array('data' => 1),
array('data' => 1),
array('data' => 1),
array('data' => 0)
)
);
// Store the result
$result_array = array();
// Count each unique value for 'data'
foreach ($data['some1'] as $key => $value) {
if ( ! isset($result_array[$value['data']])) {
$result_array[$value['data']] = 0;
}
$result_array[$value['data']]++;
}
// Display unqiue results & their respective counts
print_r($result_array);
Example: https://eval.in/862097

PHP Insert array into multidimensional array is overwrite

I´m trying to insert arrays into other array, the problem is that when I call the array_push() method it overwrites the last one element of my array, then I just get an array with data of one array (the last one):
$users_data = [];
$resultSize = count($result);
$data = $result;
for ($i = 0; $i < $resultSize; $i++) {
$person = [
'nombre' => $result[$i]['nombre'],
'apellido' => $result[$i]['apellido'],
];
array_push($users_data, $person);
// $users_data = $person; I also have tried with this method.
};
I just receive one object with this:
Object {nombre: jane, apellido: doe}
What is going wrong?
It shud be like this,
$person['nombre'][$i] = $result[$i]['nombre'];
$person['apellido'][$i] = $result[$i]['apellido'];
^ you have missed this index.
Then no need of array_push(). you can directly assign persons to user_data
Or like this :
for ($i = 0; $i < $resultSize; $i++) {
$users_data['nombre'][] = $result[$i]['nombre'];
$users_data['apellido'][] = $result[$i]['apellido'];
};

how to add letters of the name as array elements in php?

i am receiving the name from the $request in php.I want to do something like to add all the letters of the name in the array during the request e.g
$name=$_request['name'];
say $name='test';
i want to save it in an array in this format as array("t","e","s","t").
how can i do it ?
str_split is your friend.
$split_string = str_split($name);
It may be sufficient for you to access the string directly as an array, without the need to format the data:
$a = 'abcde';
echo $a[2];
Will output
c
However you won't be able to perform some array operations, such as foreach
see the php site
so it would be like
$name= 'test';
$arr1 = str_split($name);
would result in a array like:
Array
(
[0] => t
[1] => e
[2] => s
[3] => t
)
Here you go
$i = 0;
while(isset($name[$i])) {
$nameArray[$i] = $name[$i];
$i++;
}
Try this:
$letters = array();
for (int $i=0; $i < strlen($name); $i++){
$letters[] = $name[$i];
}
and you can access it with:
for (int $i=0; $i < strlen($letters); $i++){
$letters[$i];
}

PHP Array. Change every row data in table to a string then pass to array

I am trying to use to a loop to pull all rows from a table, and change every row to a string then pass to an array. Here is the script I am currently working on.
PHP:
function toggleLayers(){
$toggleArray = array($toggle);
for($i=0;$i<$group_layer_row;$i++){
$toggle=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray($toggle);
}
}
Right now it only returns a string without passing to the array. Been looking and can't seem to find anywhere or anyone that can explain this to me in plain english.
Hope you can help. Thanks
I have no idea what vars are what in your example, but if you wanted to loop through an array and change its contents, here's how i'd do it:
$myArray = array( 'thing', 'thing2' );
// the ampersand will pass by reference, i.e.
// the _Actual_ element in the array
foreach( $myArray as &$thing ){
$thing .= " - wat?!";
}
print_r( $myArray );
will give you
[0] =>
'thing - wat?!'
[1] =>
'thing2 - wat?!'
I think you will gonna change your code to something like this:
$toggleArray = array();
for ($i = 0; $i < $group_layer_row; $i++) {
// push your string onto the array
$toggleArray[] = mb_convert_encoding(mssql_result($rs_group_layer, $i, 0), "UTF-8", "SJIS") . "_" . mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1), "UTF-8", "SJIS");
}
return $toggleArray;

Categories