I have this type of Array
Array
(
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
);
I need to convert this array into following type of json
data: [
['Samy Jeremiah',55 ],
['Nelson Owen',93 ],
['McMaster Ashlie',88 ] ,
['Marsh Harlow',97 ] ,
['Macfarquhar Aiden',95 ],
['Lowe Sophie',91 ]
]
Try this
<?php
$yourArray = array(
'0' => 'Samy Jeremiah,55',
'1' => 'Nelson Owen,93',
'2' => 'McMaster Ashlie,88',
'3' => 'Marsh Harlow,97',
'4' => 'Macfarquhar Aiden,95',
'5' => 'Lowe Sophie,91',
);
#Check output 01
//print_r($yourArray);
foreach ($yourArray as $value) {
$explodeValue = explode( ',', $value );
$newName []= array($explodeValue[0] => $explodeValue[1]);
}
#Check output 02
//print_r($newName);
#Check output 03
echo(json_encode($newName));
?>
PHPFiddle Preview
Output 01
Array (
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
)
Output 02
Array (
[0] => Array ( [Samy Jeremiah] => 55 )
[1] => Array ( [Nelson Owen] => 93 )
[2] => Array ( [McMaster Ashlie] => 88 )
[3] => Array ( [Marsh Harlow] => 97 )
[4] => Array ( [Macfarquhar Aiden] => 95 )
[5] => Array ( [Lowe Sophie] => 91 )
)
Output 03
[
{"Samy Jeremiah":"55"},
{"Nelson Owen":"93"},
{"McMaster Ashlie":"88"},
{"Marsh Harlow":"97"},
{"Macfarquhar Aiden":"95"},
{"Lowe Sophie":"91"}
]
Your desired result is an array of arrays. You have to split each entry of your array into 2 entities and push them as an array into a new array, then json_encode() the new array.
This php-snippet only works, if your input is consistantly an array of strings, containing each one comma as separator between name and int-value:
$arr2 = array();
foreach($arr1 as $e) {
list($name, $val) = explode(',', $e);
$arr2[] = array($name, (int)$val);
}
echo json_encode($arr2);
Use below code
$data = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$res = array();
foreach($data as $e) {
$list = explode(',', $e);
$res[] = array($list[0], $list[1]);
}
echo json_encode(['data'=>$arr2]);
Output
{"data":[
["Samy Jeremiah",55],
["Nelson Owen",93],
["McMaster Ashlie",88],
["Marsh Harlow",97],
["Macfarquhar Aiden",95],
["Lowe Sophie",91]
]
}
Using the json_encode you can achieve what you want.
Suppose your array name is $arr, so now apply the json_encode.
echo json_encode(array('data'=>$arr)); //your json will be print here
Real time Example:
$arr = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$new_arr = array();
foreach($arr as $k => $val){
$na = explode(",", $val);
$na[0] = "'".$na[0]."'";
$value = implode(",", $na);
$new_arr[$k] = $value;
}
echo json_encode(array("data" => $new_arr));
Related
I have the following PHP array
[1] => Array
(
[0] => 9780881220766
[1] => 0881220760
)
[2] => Array
(
[0] => 9780141374284
[1] => 0141374284
)
[3] => Array
(
[0] => 057305133X
[1] => 9780573051333
))
I would like the output to be as follows:
[0] => 9780881220766
[1] => 0881220760
[2] => 9780141374284
[3] => 0141374284
[4] => 057305133X
[5] => 9780573051333
I tried using array_values but I'm not getting any output.
I also tried to extract the values using a foreach loop:
foreach ($rawIsbns as $isbnKey => $isbnValue){
$formattedIsbns[] = $isbnValue;
}
However, I'm not managing.
$a = array();
foreach ($array as $tmp) {
if (is_array($tmp)) $a = array_merge($a, $tmp);
}
Created this function that allows you to merge 1 or more arrays together into the format you asked for:
function sortarr(...$arr){
$tmparr = [];
foreach($arr as $aa) foreach($aa as $a) $tmparr = array_merge($tmparr, $a);
return $tmparr;
}
Example Usage:
<?php
# First array provided
$array = array(
[
"9780881220766",
"0881220760"
],
[
"9780141374284",
"0141374284"
],
[
"057305133X",
"9780573051333"
]
);
# Second array just to show how you can input more than 1 array into the function
$array2 = array(
[
"6234808972234",
"67834757"
],
[
"0287568924344234",
"234690543"
],
[
"34565786978099x",
"3569876546"
]
);
function sortarr(...$arr){
# Declare our temp array
$tmparr = [];
# Iterates through each of the arrays inside the array(s) provided
foreach($arr as $aa) foreach($aa as $a) $tmparr = array_merge($tmparr, $a);
# Return the results
return $tmparr;
}
print_r( sortarr($array, $array2) );
Results:
Array
(
[0] => 9780881220766
[1] => 0881220760
[2] => 9780141374284
[3] => 0141374284
[4] => 057305133X
[5] => 9780573051333
[6] => 6234808972234
[7] => 67834757
[8] => 0287568924344234
[9] => 234690543
[10] => 34565786978099X
[11] => 3569876546
)
Live Demo: http://sandbox.onlinephpfunctions.com/code/838a108498f446ae4a5f8e42fa441ec11941c567
I managed to solve the problem by initializing an array and adding values of subsequent nested arrays using array_push
function isbns($rawIsbns) {
$prevArrayValues = null;
foreach ($rawIsbns as $value) {
if (!isset($prevArrayValues)) {
$prevArrayValues = []; //initiallise first value unless initialized
}
if (empty($value)) {
$return = []; //disregard empty values
} else {
$return = $value; // add arrays to existing array
}
$prevArrayValues = array_merge($prevArrayValues, $return);
}
return $prevArrayValues;
}
This is my form input $data, i want this keep this input.
$data = "39X3,29X5";
this my code convert string to array
$data = explode(",", $data);
$out = array();
$step = 0;
foreach($data as $key=>$item){
foreach(explode('X',$item) as $value){
$out[$key][$step++] = $value;
}
print '<pre>';
print_r($out);
print '</pre>';
result
Array
(
[0] => Array
(
[0] => 39
[1] => 3
)
[1] => Array
(
[2] => 29
[3] => 5
)
)
but i want change the keys and fix this for support query builder class
$this->db->insert_batch('mytable',$out).
Like this.
array
(
array
(
'number' => 39
'prize' => 3
),
array
(
'number' => 29
'prize' => 5
)
)
i try hard and confuse using loop.
So you need to remove inner foreach and put relevant values into array.
foreach($data as $key=>$item){
$exp = explode('X', $item);
$out[$key] = [
'number' => $exp[0],
'prize' => $exp[1]
];
}
Check result in demo
change your foreach loop to the following:
foreach($data as $key=>$item){
$temp = explode('X',$item);
$out[] = ['number' => $temp[0] , 'prize' => $temp[1]];
}
i want to know if it's possible to change an array structure, currently i'm receiving this array:
[{"ano":["2004","2006"]},{"ano":["2006",""]},{"ano":["2011",""]},{"ano":["2013",""]}]
I need those dates split one by row like this:
[{"ano":"2004"},{"ano":"2006"},{"ano":"2006"},{"ano":"2011"}]
So, basically i'm think i could clean empty and duplicated values, and then split the array or something?
I'm using PHP and MySQL SELECT to return those values like this:
while($ano = $pegaAno->fetchObject()){
$ar1 = array("ano" => $ano->inicio);
$ar2 = array("ano" => $ano->fim);
$result = array_merge_recursive($ar1, $ar2);
//print_r($result);
array_push($return_arr,$result);
}
Any help please?
while($ano = $pegaAno->fetchObject())
array_push($return_arr, array("ano" => $ano->inicio), array("ano" => $ano->fim));
$return_arr = array_unique($return_arr);
Perhaps you want something like this? So you can have an array as
0 => [ "ano" => value ]
1 => [ "ano" => value ]
2 => [ "ano" => value ]
//etc...
You may also try this code
$input[0]['anno'] = array("2004","2006");
$input[1]['anno'] = array("2008","");
$input[2]['anno'] = array("2002","2006");
$input[3]['anno'] = array("2004","2013");
$arr = array();
foreach ($input as $value) {
foreach ($value as $key => $value1) {
foreach ($value1 as $value2) {
$arr[] = $value2;
}
}
}
$resulted = array_filter(array_unique($arr));
$resulted_array = array();
foreach ($resulted as $value) {
$resulted_array[][$mainkey] = $value;
}
print_r($resulted_array);
//RESULT
Array
(
[0] => Array
(
[anno] => 2004
)
[1] => Array
(
[anno] => 2006
)
[2] => Array
(
[anno] => 2008
)
[3] => Array
(
[anno] => 2002
)
[4] => Array
(
[anno] => 2013
)
)
I have an array like this :
Array (
[0] => Array (
[tsk_hours_spent] => 23425.00
)
[1] => Array (
[tsk_hours_spent] => 2.00
)
[2] => Array (
[tsk_hours_spent] => 0.00
)
[3] => Array (
[tsk_hours_spent] => 0.00
)
[4] => Array (
[tsk_hours_spent] => 0.20
)
)
I want results seperated based on '.' into two array
ie.,
Before dot one array and after dot one array
eg:
First array will be : 23425,2,0,0,0
Second array will be : 00,00,00,00,20
Try This
<?php
$tsk_hours_spent = array(array('tsk_hours_spent'=>'23425.00'),array('tsk_hours_spent'=>'2.00'),array('tsk_hours_spent'=>'0.00'),array('tsk_hours_spent'=>'0.00'),array('tsk_hours_spent'=>'0.00'));
$finalArray = array();
foreach($tsk_hours_spent as $key){
$tmp = (explode('.',$key['tsk_hours_spent']));
$finalArray['partOne'][] = $tmp[0];
$finalArray['partSecond'][] = $tmp[1];
}
echo implode(',',$finalArray['partOne']);
echo "</br>";
echo implode(',',$finalArray['partSecond']);
Try this,
$array=array(array('tsk_hours_spent' => '23425.00'),
array('tsk_hours_spent' => '2.00'),
array('tsk_hours_spent' => '0.00'),
array('tsk_hours_spent' => '0.00'),
array('tsk_hours_spent' => '0.20'));
$hour=array();
$minut=array();
foreach($array as $value)
{
$temp=explode('.', $value['tsk_hours_spent'].' ');
array_push($hour, $temp[0]);
array_push($minut, $temp[1]);
}
print_r($hour);
print_r($minut);
Output
Array
(
[0] => 23425
[1] => 2
[2] => 0
[3] => 0
[4] => 0
)
Array
(
[0] => 00
[1] => 00
[2] => 00
[3] => 00
[4] => 20
)
Works with floating point numbers as opposed to strings in answers above
$arr = array();
$arr[] = array('tsk_hours_spent'=>23425.00); //floating point numbers
$arr[] = array('tsk_hours_spent'=>2.00);
$arr[] = array('tsk_hours_spent'=>0.00);
$arr[] = array('tsk_hours_spent'=>0.00);
$arr[] = array('tsk_hours_spent'=>0.20);
$first = array();
$second = array();
foreach($arr as $k => $v){
$ex = explode('.',strval($v['tsk_hours_spent']));
$first[] = $ex[0];
$second[] = isset($ex[1])?str_pad($ex[1],2,0,STR_PAD_RIGHT):'00';
}
print_r($first);
print_r($second);
Array
(
[0] => 23425
[1] => 2
[2] => 0
[3] => 0
[4] => 0
)
Array
(
[0] => 00
[1] => 00
[2] => 00
[3] => 00
[4] => 20
)
A functional approach to this problem:
$arr1 = $arr2 = array();
array_walk($data, function(&$value) use (&$arr1, &$arr2) {
$parts = explode('.', $value['tsk_hours_spent']);
$arr1[] = $parts[0];
$arr2[] = $parts[1];
});
echo implode(',', $arr1);
echo implode(',', $arr2);
Simpler solution using foreach:
$arr1 = $arr2 = array();
foreach ($data as $arr) {
list($beforedot, $afterdot) = explode('.', $arr['tsk_hours_spent']);
$arr1[] = $beforedot;
$arr2[] = $afterdot;
}
echo implode(',', $arr1);
echo implode(',', $arr2);
Demo
Addition to #sisimaster more shorter code.
Considering $a is your required array
for ($i=0;$i<=count($a)-1;$i++){
list($whole[], $decimal[]) = explode('.', $a[$i]['tsk_hours_spent']);
}
$wholenumber=implode(",",$whole); //23425,2,0,0,0
$decimalnumber=implode(",",$decimal);//00,00,00,00,00
Considering this array
Array
(
[0] => Array
(
[id] => 51
[category_id] => 37
[title] => Sims
)
[1] => Array
(
[id] => 37
[category_id] => 26
[title] => Blackberry
)
[2] => Array
(
[id] => 26
[category_id] => 0
[title] => Mobile Device
)
I would like to be able to print out:
Mobile Device > Blackberry > Sims
Based on the relationship between category_id and id.
Can you use the id as the key into the array? It will make your life a bit simpler. For example, if you define your array:
Array
(
[51] => Array
(
[id] => 51
[category_id] => 37
[title] => Sims
)
[37] => Array
(
[id] => 37
[category_id] => 26
[title] => Blackberry
)
[27] => Array
(
[id] => 26
[category_id] => 0
[title] => Mobile Device
)
Then you can write code like:
//assume $a is your array, defined above
//and that you have used the id for the array key
$id = 51
do {
print $a['title'];
$id = $a['category_id'];
}while($id != 0);
EDIT: array_multisort probably isn't cleanest way to do this.
<?php
$array = Array(
array('id' => 51, 'category_id' => 37, 'title' => 'Sims'),
array('id' => 37, 'category_id' => 26, 'title' => 'Blackberry'),
array('id' => 26, 'category_id' => 0, 'title' => 'Mobile Device'));
// First build an associative array ID->Object
$map = array();
foreach( $array as $value )
{
$map[$value['id']] = $value;
}
// Then build your path
$path = array();
$value = $array[0];
while( true )
{
$path[] = $value['title'];
if( $value['category_id'] == 0 )
{
break;
}
$value = $map[$value['category_id']];
if( !isset($value) )
{
die("Data Inconsistency");
}
}
// Display path
echo implode(array_reverse($path), ' > ');
?>
Try array_multisort()
Does your original array also contains entries that are to be left out?
If not, use this:
$sort_array = array();
foreach ($original_array as $key => $value) {
$sort_array[] = $value['category_id'];
}
array_multisort($sort_array, SORT_ASC, $original_array);
The above will sort $original_array based on the category_id index.
If your array contains entries that have nothing to do with the rest, and you want to leave them out, you have to use something like this:
// remap keys based on category_id
$parts = array();
foreach ($original_array as $array) {
$parts[$array['category_id']] = $array;
}
// build tree list
$category_id = 0;
$result = array();
while (isset($parts[$category_id])) {
$result[] = $parts[$category_id]['title'];
$category_id = $parts[$category_id]['id'];
}
echo implode(' > ', $result);