I have an arrays like follows:
Array
(
[option] => nos
[optioncost] => 10
)
Array
(
[option] => opts
[optioncost] => 20
)
Array
(
[option] => opts
[optioncost] => 30
)
need to convert this as like the following json format
[{"option":nos,"optioncost":10},{"option":opts,"optioncost":20},{"option":optse,"optioncost":30}]
Try this code :
<?php
$arr = array();
$arr[] = array('option' => 'nos',
'optioncost' => 10
);
$arr[] = array('option' => 'opts',
'optioncost' => 20
);
$arr[] = array('option' => 'optse',
'optioncost' => 30
);
echo json_encode($arr);
?>
Output :
[{"option":"nos","optioncost":10},{"option":"opts","optioncost":20},{"option":"opts","optioncost":30}]
Hope this helps !
The json example you've provided isn't valid because strings aren't quoted (nos / opts), something you could have easily tested on any online json validator.
You'll need to construct proper arrays - where strings are "quoted" - and use the json_encode() function, i.e.:
$arr1 = ['option' => "nos", 'optioncost' => 10];
$arr2 = ['option' => "opts", 'optioncost' => 20];
$arr3 = ['option' => "opts", 'optioncost' => 30];
echo json_encode([$arr1, $arr2, $arr3]);
# [{"option":"nos","optioncost":10},{"option":"opts","optioncost":20},{"option":"opts","optioncost":30}]
DEMO
Note:
Strings need to be quoted, but floats, ints or bools don't.
Related
I get data from this code.
foreach ($datas as $data){
echo $data['product_number']."<br>";
}
Then it will show the data like :
MP/9998/00012
00089
12009
290989
But I want to change my data become
12
120
89
12009
290989
I edit the question. Here's my question before:
I have this array
$data = ["00012", "00120", "00089", "12009", "290989"].
This array have contain at least 5 character. How can I get that array data become
[12, 120, 89, 12009, 290989]
Thank You.
simple use array_map and intval
$data= array('00012','00120','00089','12009','290989');
$new = array_map('intval',$data); //intval function applied to each element in the array
print_r($new);
Update 1: Apply intval
foreach ($datas as $data){
echo intval($data['product_number'])."<br>";
}
Update 2: use filter_var
$str = 'MP/000090';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo intval($int);
Try this:
<?php
$data = array("00012", "00120", "00089", "12009", "290989" );
foreach( $data as $v )
{
echo ltrim($v, "0") . "\n";
}
Live Demo
Output
12
120
89
12009
290989
This will always return your last string of numbers (omitting any preceding zeros) in each element:
Code: (Demo)
$data=array('00012','00120','00089','12009','290989','MP/000090','MP/9998/0023028');
$data=array_map(function($v){return preg_match('~0*\K\d+$~',$v,$out)?$out:'fail';},$data);
var_export($data);
Output:
array (
0 =>
array (
0 => '12',
),
1 =>
array (
0 => '120',
),
2 =>
array (
0 => '89',
),
3 =>
array (
0 => '12009',
),
4 =>
array (
0 => '290989',
),
5 =>
array (
0 => '90',
),
6 =>
array (
0 => '23028',
),
)
I need to convert my array but I don't have extended experience to complete this task.
Please help me to find a way to do please?
I have this:
Array(
[0] => Array
(
[BTC] => 0.07634
)
[1] => Array
(
[ETH] => 0.00103
)
[2] => Array
(
[LTC] => 0.006787
)
[3] => Array
(
[XMR] => 0.006351
)
And I need this:
Array(
[BTC] => 0.07634
[ETH] => 0.00103(
[LTC] => 0.006787
[XMR] => 0.006351
[ZEC] => 0.00144
[MD_DT_CAD] => 2017-08-14 02:16:44
)
You have following
$data =array(
array("BTC" => 0.07634),
array("ETH" => 0.00103),
array("LTC" => 0.006787),
array("XMR" => 0.006351)
);
You can achieve your result by following.
<?php
$data =array(
array("BTC" => 0.07634),
array("ETH" => 0.00103),
array("LTC" => 0.006787),
array("XMR" => 0.006351)
);
foreach($data as $value){
foreach ($value as $key => $value1) {
$new_arr[$key] = $value1;
}
}
echo "<pre>";
print_r($new_arr);
?>
Simple use call_user_func_array with array_merge
$array = Array("0" => Array("BTC" => 0.07634),"1" => Array("ETH" => 0.00103),"2" => Array("LTC" => 0.006787),"3" => Array("XMR" => 0.006351));
$new_array = call_user_func_array('array_merge', $array);
print_r($new_array);
<?php $array=array(array("BTC" => 0.07634),array("ETH" => 0.00103),array("LTC" => 0.006787),
array("XMR" => 0.006351));
//echo print_r($array);
$array2 = array_reduce($array, 'array_merge', array());//or call_user_func_array('array_merge', $array);
echo print_r($array2);
?>
Assuming your array is called $array :
$new_array = array_merge(... $array);
Explaination : array_merge() takes an undefined amount of different arrays as parameters, gathers them as entries in a single array by using the splat operator (...) and then merges all these arrays in one before returning it.
Calling that function and passing it a single array and using the splat operator in the calling too makes that single array to be the single array containing the arrays to merge on which the function will work. By doing that, you can have the function to merge sub_arrays of an array you already have without calling additional functions.
I have a multidimensional array. Like this.
Array
(
[38] => Array
(
[quantity] => 1
[price] => 149
[product_code] => 4578425
)
[39] => Array
(
[quantity] => 2
[price] => 300
[product_code] => 4578426
)
)
I want to create query string from these values like
https://www.domain.com/checkout.php?PRODS=4578425,4578426&QTY=1,2&CART=1
Without using loops...
I don't think AFAIK, it is possible, since you have arrays in array, so using implode won't help. But, using loops, yea.
Use this code:
$prods = array();
$qty = array();
foreach ($array as $item)
{
$prods[] = $item["product_code"];
$qty[] = $item["quantity"];
}
echo 'https://www.domain.com/checkout.php?PRODS=', implode(',', $prods),'&QTY=', implode(',', $qty),'&CART=1';
you can use implode() method
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
Yes i think there is a way,
You can use serialize to put it in a string and then unserialize to get it back to an array like this:
<?php
$arr = Array
(
38 => Array
(
'quantity' => 1,
'price' => 149,
'product_code' => 4578425
),
39 => Array
(
'quantity' => 2,
'price' => 300,
'product_code' => 4578426
)
);
$newarr = 'https://www.domain.com/checkout.php?string=';
$newarr .= serialize($arr);
?>
then you have this result:
https://www.domain.com/checkout.php?string=a:2:{i:38;a:3:{s:8:"quantity";i:1;s:5:"price";i:149;s:12:"product_code";i:4578425;}i:39;a:3:{s:8:"quantity";i:2;s:5:"price";i:300;s:12:"product_code";i:4578426;}}a:2:{i:38;a:3:{s:8:"quantity";i:1;s:5:"price";i:149;s:12:"product_code";i:4578425;}i:39;a:3:{s:8:"quantity";i:2;s:5:"price";i:300;s:12:"product_code";i:4578426;}}
No loops but it is not pretty!!!
If you wish to use this inside url I have to warn you. The url get method is only intended for short information like id's or other key values. If your url gets over 2000 characters most web-servers would have problems with it. Not sure if that was your intention.
I have an array that looks like
Array
(
[1] => Array
(
[0] => Date
[1] => Action
)
[2] => Array
(
[0] => 2011-01-22 11:23:19
[1] => SHARE_TWEET
)
[3] => Array
(
[0] => 2011-01-22 11:23:19
[1] => SHARE_FACEBOOK
)
and many other different values (about 10), what I want to do is I want to count the number of times a string is in the array. I was going to use array_count_values but it doesn't count multidimensional arrays.
Any other options?
This could be done by first flattening the array, and then using array_count_values() on it:
For flattening, here is the trick:
$array = call_user_func_array('array_merge', $arrays);
And then:
$counts = array_count_values($array);
Output:
array (
'Date' => 1,
'Action' => 1,
'2011-01-22 11:23:19' => 2,
'SHARE_TWEET' => 1,
'SHARE_FACEBOOK' => 1,
)
Full code:
$array = call_user_func_array('array_merge', $arrays);
var_export(array_count_values($array));
Any time you're dealing with arrays, especially with loops in PHP I can't string enough suggest you look at the array documentation, You'd be suprised how quickly you realise most of the loops in your code is unnecessary. PHP has a built in function to achieve what you're after called array_walk_recursive. And since you're using PHP5 you can use closures rather that create_function (which can be very troublesome, especially to debug, and can't be optimised by the PHP interpreter afik)
$strings = array();
array_walk_recursive($arr, function($value, $key) use (&$strings) {
$strings[$value] = isset($strings[$value]) ? $strings[$value]+1 : 1;
});
I know, unary statements aren't always clear, but this one is simple enough, but feel free to expand out the if statement.
The result of the above is:
print_r($strings);
Array
(
[Date] => 1,
[Action] => 1,
[2011-01-22 11:23:19] => 2,
[SHARE_TWEET] => 1,
[SHARE_FACEBOOK] => 1,
)
Pseudo Code
$inputArray = // your array as in the example above
foreach ($inputArray as $key => $value) {
$result[$value[1]] = $result[$value[1]] + 1;
}
var_dump($result);
Here is a way to do the job:
$arr = Array (
1 => Array (
0 => 'Date',
1 => 'Action'
),
2 => Array (
0 => '2011-01-22 11:23:19',
1 => 'SHARE_TWEET'
),
3 => Array (
0 => '2011-01-22 11:23:19',
1 => 'SHARE_FACEBOOK'
)
);
$result = array();
function count_array($arr) {
global $result;
foreach($arr as $k => $v) {
if (is_array($v)) {
count_array($v);
} else {
if (isset($result[$v])) {
$result[$v]++;
} else {
$result[$v] = 1;
}
}
}
}
count_array($arr);
print_r($result);
output:
Array
(
[Date] => 1
[Action] => 1
[2011-01-22 11:23:19] => 2
[SHARE_TWEET] => 1
[SHARE_FACEBOOK] => 1
)
I have the following array, which I would like to reindex so the keys are reversed (ideally starting at 1):
Current array (edit: the array actually looks like this):
Array (
[2] => Object
(
[title] => Section
[linked] => 1
)
[1] => Object
(
[title] => Sub-Section
[linked] => 1
)
[0] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
How it should be:
Array (
[1] => Object
(
[title] => Section
[linked] => 1
)
[2] => Object
(
[title] => Sub-Section
[linked] => 1
)
[3] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
If you want to re-index starting to zero, simply do the following:
$iZero = array_values($arr);
If you need it to start at one, then use the following:
$iOne = array_combine(range(1, count($arr)), array_values($arr));
Here are the manual pages for the functions used:
array_values()
array_combine()
range()
Why reindexing? Just add 1 to the index:
foreach ($array as $key => $val) {
echo $key + 1, '<br>';
}
Edit After the question has been clarified: You could use the array_values to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.
This will do what you want:
<?php
$array = array(2 => 'a', 1 => 'b', 0 => 'c');
array_unshift($array, false); // Add to the start of the array
$array = array_values($array); // Re-number
// Remove the first index so we start at 1
$array = array_slice($array, 1, count($array), true);
print_r($array); // Array ( [1] => a [2] => b [3] => c )
?>
You may want to consider why you want to use a 1-based array at all. Zero-based arrays (when using non-associative arrays) are pretty standard, and if you're wanting to output to a UI, most would handle the solution by just increasing the integer upon output to the UI.
Think about consistency—both in your application and in the code you work with—when thinking about 1-based indexers for arrays.
You can reindex an array so the new array starts with an index of 1 like this;
$arr = array(
'2' => 'red',
'1' => 'green',
'0' => 'blue',
);
$arr1 = array_values($arr); // Reindex the array starting from 0.
array_unshift($arr1, ''); // Prepend a dummy element to the start of the array.
unset($arr1[0]); // Kill the dummy element.
print_r($arr);
print_r($arr1);
The output from the above is;
Array
(
[2] => red
[1] => green
[0] => blue
)
Array
(
[1] => red
[2] => green
[3] => blue
)
Well, I would like to think that for whatever your end goal is, you wouldn't actually need to modify the array to be 1-based as opposed to 0-based, but could instead handle it at iteration time like Gumbo posted.
However, to answer your question, this function should convert any array into a 1-based version
function convertToOneBased( $arr )
{
return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
}
EDIT
Here's a more reusable/flexible function, should you desire it
$arr = array( 'a', 'b', 'c' );
echo '<pre>';
print_r( reIndexArray( $arr ) );
print_r( reIndexArray( $arr, 1 ) );
print_r( reIndexArray( $arr, 2 ) );
print_r( reIndexArray( $arr, 10 ) );
print_r( reIndexArray( $arr, -10 ) );
echo '</pre>';
function reIndexArray( $arr, $startAt=0 )
{
return ( 0 == $startAt )
? array_values( $arr )
: array_combine( range( $startAt, count( $arr ) + ( $startAt - 1 ) ), array_values( $arr ) );
}
A more elegant solution:
$list = array_combine(range(1, count($list)), array_values($list));
The fastest way I can think of
array_unshift($arr, null);
unset($arr[0]);
print_r($arr);
And if you just want to reindex the array(start at zero) and you have PHP +7.3 you can do it this way
array_unshift($arr);
I believe array_unshift is better than array_values as the former does not create a copy of the array.
Changelog
Version
Description
7.3.0
This function can now be called with only one parameter. Formerly, at least two parameters have been required.
-- https://www.php.net/manual/en/function.array-unshift.php#refsect1-function.array-unshift-changelog
$tmp = array();
foreach (array_values($array) as $key => $value) {
$tmp[$key+1] = $value;
}
$array = $tmp;
It feels like all of the array_combine() answers are all copying the same "mistake" (the unnecessary call of array_values()).
array_combine() ignores the keys of both parameters that it receives.
Code: (Demo)
$array = [
2 => (object)['title' => 'Section', 'linked' => 1],
1 => (object)['title' => 'Sub-Section', 'linked' => 1],
0 => (object)['title' => 'Sub-Sub-Section', 'linked' => null]
];
var_export(array_combine(range(1, count($array)), $array));
Output:
array (
1 =>
(object) array(
'title' => 'Section',
'linked' => 1,
),
2 =>
(object) array(
'title' => 'Sub-Section',
'linked' => 1,
),
3 =>
(object) array(
'title' => 'Sub-Sub-Section',
'linked' => NULL,
),
)
If you are not trying to reorder the array you can just do:
$array = array_reverse( $array );
and then call it once more to get it back to the same order:
$array = array_reverse( $array );
array_reverse() reindexes as it reverses. Someone else showed me this a long time ago. So I can't take credit for coming up with it. But it is very simple and fast.
The result is an array with indexed keys starting from 0. https://3v4l.org/iQgVh
array (
0 =>
(object) array(
'title' => 'Section',
'linked' => 1,
),
1 =>
(object) array(
'title' => 'Sub-Section',
'linked' => 1,
),
2 =>
(object) array(
'title' => 'Sub-Sub-Section',
'linked' => NULL,
),
)
Here's my own implementation. Keys in the input array will be renumbered with incrementing keys starting from $start_index.
function array_reindex($array, $start_index)
{
$array = array_values($array);
$zeros_array = array_fill(0, $start_index, null);
return array_slice(array_merge($zeros_array, $array), $start_index, null, true);
}