Multidimensional array to string php - php

I have below array and i am trying to convert to string separated with comma.
$users_array = Array
(
[0] => Array
(
[0] => Array
(
[user_id] => 1
)
[1] => Array
(
[user_id] => 5
)
)
[1] => Array
(
[0] => Array
(
[user_id] => 6
)
[1] => Array
(
[user_id] => 13
)
)
)
Then i tried to convert in string with foreach
for($i = 0; $i < count($users_array); $i++){
$xyz[] = implode(",",$users_array[$i]);
}
$users = implode(',',$xyz);
But it throw error Message: Array to string conversion
How can i convert it to string like 1,5,6,13?
Thank you,

for($i = 0; $i < count($users_array); $i++){
for($j = 0; $j < count($users_array[$i]; $j++)) {
$xyz[] = $users_array[$i][$j]["user_id"];
}
}
$users = implode(',',$xyz);

$user_ids = array();
foreach($users_array as $val){
foreach($val as $v)){
array_push($user_ids,$v['user_id']);
}
}
$users = implode(',',$user_ids);
This code is very easy and also use for as per your requirement.

hey #rjcode in php if you want to convert an array to comma separated
string so use function implode(separation letter, $array) and for vice
versa means string to an array so use function explode(separation
letter, string)
for your case use use implode() so for your code try below one
<?php
for($i = 0; $i < count($users_array); $i++){
for($j = 0; $j < count($users_array[$i]; $j++)) {
$xyz[] = $users_array[$i][$j]["user_id"];
}
}
$users = implode(',',$xyz);
?>

Related

Building multidimensional array with input from 2 arrays

It works fine creating level-1, but when level-2 is being created, it only updates the first letter of index [1].
Code:
// Position [Level-1]
$taxonomy_id = [
"id_no_1",
"id_no_2",
"id_no_3",
];
// Position [Level-2]
$titles = [
"title_1",
"title_2",
"title_3",
];
$array = [];
for ($i = 0; $i < count($taxonomy_id); $i++) {
//Construct level-1
$array[] = $taxonomy_id["{$i}"];
//Construct level-2
$array["{$i}"]["{$i}"] = $titles["{$i}"];
}
print_r($array);
Result:
(
[0] => td_no_1
[1] => it_no_2
[2] => id_no_3
)
Wanted result:
Array
(
[id_no_1] => Array
(
[0] => title_1
)
[id_no_2] => Array
(
[0] => title_2
)
)
You would be better off creating the sub arrays in one go, you can also simplify "{$i}" with $i...
for ($i = 0; $i < count($taxonomy_id); $i++) {
$array[$taxonomy_id[$i]] = [$titles[$i]];
}

Push the output of a for loop into an array

I am trying to push the output of a for loop into an array but I am not being able to do so. Following is the code that I have written:
<?php
$n = 14;
for ($i = 2; $i <= $n; $i++)
{
for ($j = 2; $j <= $n; $j++)
{
if ($i%$j == 0) // if remainder of $i divided by $j is equal to zero, break.
{
break;
}
}
if ($i == $j) //
{
$form = $i;
//echo $form;
$numArray = array();
array_push($numArray, $form); // Here I am trying to push the contents from the `$form` variable into the `$numArray`
print_r($numArray);
}
}
?>
The output that I obtain through this is:
Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 5 ) Array ( [0] => 7 ) Array ( [0] => 11 ) Array ( [0] => 13 )
Here, we see that the array index basically remains the same, so it has no scope for future use. So, how can I make this seem like as shown below:
Array ( [0] => 2 ) Array ( [1] => 3 ) Array ( [2] => 5 ) Array ( [3] => 7 ) Array ( [4] => 11 ) Array ( [5] => 13 )
Please note that, $n in the code can be any number less than 101 and greater than 1. Thank you for your precious time put into reading and trying to helping me out. :)
The $numArray should be declared once, not every time in the loop. And you can simply add value to the array by using expression like: $numArray[] = $i;
Try this code:
<?php
$numArray = array();
$n = 14;
for ($i = 2; $i <= $n; $i++) {
for ($j = 2; $j <= $n; $j++) {
if ($i % $j == 0) { // if remainder of $i divided by $j is equal to zero, break.
break;
}
}
if ($i == $j) {
$numArray[] = $i;
}
}
print_r($numArray);

How do I create arrays within a nested for loop in PHP

I want to create an array from this nested for loop
for($i = 0; $i < 2; $i++){
for($j = 0; $j < 3; $j++){
$dis = $i + $j;
createArr($dis, $i);
}
echoArr($i);
}
To do this I created a function called createArr() which receives $dis and the $i iterator.
$arr= array();
function createArr($dis, $i){
$arr= 'arr'.$i;
array_push($arr, $dis);
return $arr;
}
I want $arr to be the name of the array in this example during the first iteration of the nested for loop $i = 0. Thus I want the name of the array to be $arr0 with the array_push function pushing all the elements of $j while $i = 0 then to store into another array when the second iteration of $i when it starts at$arr1 to push the new elements of this array within $j's iteration when $i = 1;
function echoArr($i){
$arr= 'arr'.$i;
return $arr;
}
this last function is to echo the finished array after an iteration of $i is done.
I am not sure what you are expecting
$arr= 'arr'.$i;
array_push($arr, $dis);
to do, but array_push expects first parameter to be array,
but as you can see $arr is a string.
Is this what you need?
$arr = array();
for($i = 0; $i < 2; $i++){
for($j = 0; $j < 3; $j++){
$dis = $i + $j;
array_push($arr, createArr($dis, $i));
}
echoArr($i);
}
function createArr($dis, $i){
return array('arr'.$i => $dis);
}
print_r($arr);
//prints: Array ( [0] => Array ( [arr0] => 0 ) [1] => Array ( [arr0] => 1 ) [2] => Array ( [arr0] => 2 ) [3] => Array ( [arr1] => 1 ) [4] => Array ( [arr1] => 2 ) [5] => Array ( [arr1] => 3 ) )
What are you trying to achieve?
For the future pls describe what you would like to achieve so we can help you achieve it better.
Let me start with the first piece of code
You would like to echo the array. You are just echoing the column.
why build your own function to add something to an array?
and if you to do something with the return
$myarray[$i] = createArr($key,$value); //not a good solution, just for explaining.
Since I don't know what you like to achieve here an example of an array loop
$myarray = array();
for($i = 0; $i < 2; $i++){
for($j = 0; $j < 3; $j++){
$dis = $i + $j;
$myarray[$i][$j] = 'row:' . $i . ' column' . $j;
}
}
var_dump($myarray);
and the dump
array (size=2)
0 =>
array (size=3)
0 => string 'row:0 column0' (length=13)
1 => string 'row:0 column1' (length=13)
2 => string 'row:0 column2' (length=13)
1 =>
array (size=3)
0 => string 'row:1 column0' (length=13)
1 => string 'row:1 column1' (length=13)
2 => string 'row:1 column2' (length=13)

PHP Function for Comparing Elements in Different Arrays

I have two arrays like so (however there can be more or less than 2 (any amount)):
[0] => Array
(
[assessedUsers] => Array
(
[0] => Array
(
[scores] => Array
(
[0] => 10
[1] => 10
[2] => 10
[3] => 10
)
)
[1] => Array
(
[scores] => Array
(
[0] => 9
[1] => 10
[2] => 0
[3] => 9
)
)
)
)
Where the length of the scores array is always the same in both arrays.
I would like to take each element from each array, one by one, and average them, then append them into a new array.
For example, the output of my desired function would look like this:
[1] => Array
(
[scores] => Array
(
[0] => 9.5
[1] => 10
[2] => 5
[3] => 9.5
)
)
Is there a function that can do this, or do I need a couple nested for() loops? If I need to use forl loops how would I go about doing it? I'm a little confused on the logic behind it.
Currently what I have is:
for ($i = 0; $i < sizeof($data["assessedUsers"]); $i++) {
for ($j = 0; $j < sizeof($data["assessedUsers"][$i]["scores"]); $j++) {
}
}
and I'm a little confused as to what to where to go next. Thanks in advance!
$mean = array_map( function($a, $b) { return ($a + $b) / 2; },
$data['assessedUsers'][0]['scores'],
$data['assessedUsers'][1]['scores']
);
var_dump($mean);
And append $mean anywhere you want. Or do you have more than 2 arrays? You did not state it in your question.
ps: for any number of subarrays
$arr = array(
array('scores' => array(10,10,10,10)),
array('scores' => array(9,10,0,9)),
array('scores' => array(1,2,3,4))
);
// remove arrays from the key
$tmp = call_user_func_array( function() { return func_get_args(); },
array_map( function($a) { return $a['scores']; }, $arr)
);
// add arrays by each element
$mean = array_map( function($val, $ind) use($tmp) {
$sum = 0;
foreach($tmp as $i => $t)
$sum += $t[$ind];
return $sum / ($i + 1);
}, $tmp[0], array_keys($tmp[0]));
var_dump($mean);
Probably two loops:
$newarray();
foreach($main_array as $user) {
foreach($user['assessedUser'][0]['scores'] as $score_key => $user0_value) {
$user1_value = $user['assessedUser'][1]['scores'][$score_key];
$average = ($user1_value + $user0_value) / 2;
... stuff into new array
}
}
I have solution for you, hope this help :)
$scores = array();
for ($i = 0; $i < sizeof($data["assessedUsers"]); $i++) {
for ($j = 0; $j < sizeof($data["assessedUsers"][$i]["scores"]); $j++) {
if(isset($scores[$j])){
$scores[$j] = ($scores[$j] + $data["assessedUsers"][$i]["scores"][$j]) / ($i +1);
}else{
$scores[] = $data["assessedUsers"][$i]["scores"][$j];
}
}
}
$scores[] = $scores;
view Example :)
http://codepad.org/upPjMEym

PHP convert stdClass Object to string and reduce array with max value

I want to convert a stdClass object to string and reduce an array with the max value from the stdClass object.
This is my array:
Array
(
[135] => Array
(
[0] => stdClass Object
(
[ID] => 145
)
[1] => stdClass Object
(
[ID] => 138
)
[2] => stdClass Object
(
[ID] => 139
)
)
[140] => Array
(
[0] => stdClass Object
(
[ID] => 163
)
[1] => stdClass Object
(
[ID] => 155
)
)
Basically it should look like this:
Array
(
[135] => 139
[140] => 164
)
Is this possible? I've tried various foreach loops but i don't get it with the stdClass object...
My try so far:
foreach($ids as $k => $v) {
for($i = 0; $i < count($v); $i++) {
$idss[$i] = array()$v;
}
}
That doesn't work.
This will solve your purpose. let me know if anything goes wrong.
$ids[135][0]->ID = 145;
$ids[135][1]->ID = 135;
$ids[135][2]->ID = 155;
$ids[140][0]->ID = 125;
$ids[140][1]->ID = 135;
$idss = array();
foreach($ids as $k => $v) {
for($i = 0; $i < count($v); $i++) {
if(!#$idss[$k] || $v[$i]->ID > $idss[$k])
{
$idss[$k] = $v[$i]->ID;
}
}
}
echo "<Pre>";
print_r($idss);
die;
Already answered but here is a shorter version of this
$final_array =array();
foreach($arr as $key=>$val){
$max = max(array_keys($val));
$final_array[$key] = $val[$max]->ID ;
}
print_r($final_array);
Here $arr is your input array.
You need to do some compariosn in your inner for loop to know which one holds the max value. Here is an example :
$new_arr = array();
foreach($elements as $index => $value){
$max = -1;
$foreach($value as $obj){
if($obj->id > $max)
$max = $obj->id;
}
$new_arr [$index] = $max;
}

Categories