This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
convert string to 2D array using php
I have the string like the following:
01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16
how can I convert the above string to a defined array like the one below:
$a[0] = array('column' => array("row1" => "01", "row2"=> "05", "row3" => "07", "row4" =>"12"));
$a[1] = array('column' => array("row1" => "03", "row2"=> "04", "row3" => "09", "row4" =>"14"));
$a[2] = array('column' => array("row1" => "02", "row2"=> "06", "row3" => "08", "row4" =>"13"));
$a[3] = array('column' => array("row1" => "15", "row2"=> "10", "row3" => "11", "row4" =>"16"));
I know I should use explode function but not sure how exactly it should be implemented for this, any help would be greatly appreciated, thanks!
With that format you basically just need:
$a = array_map("str_getcsv", explode("|", $string));
That gives you an enumerated array. If you want your specific named keys, then you have'd to post-process this structure again:
foreach ($a as $i=>$row) {
$a[$i] = array("column" => array("row1"=>$row[0], "row2"=>$row[1], "row3"=>$row[2], "row4"=>$row[3]));
}
I think this is what you are looking for:
<?php
$a = array();
$str = "01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16";
$arr = explode("|", $str);
for ($i = 0; $i < count($arr); $i++) {
$a[$i] = array('column' => array());
}
for ($i=0; $i<count($arr); $i++) {
$arr2 = explode(",", $arr[$i]);
for ($j = 0; $j < count($arr2); $j++) {
$key = "row" . intval($i + 1);
$a[$j]['column'][$key] = $arr2[$j];
}
}
echo "<pre>";
var_dump($a);
?>
$sequence = "01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16";
$columns = explode("|", $sequence);
$result = array();
foreach ($columns as $i => $column)
{
$rows = explode(",", $column);
$sub_array = array();
foreach ($rows as $id => $row)
{
$sub_array["row".($id+1)] = $row;
}
$result[$i] = array('column' => $sub_array);
}
Related
This is my code:
$arr = array([], [], []);
function show() {
$numbers = array("1", "2", "3", "4", "5", "6", "7", "8", "9");
$value = [];
while (count($numbers) > 0){
for ($i = 0; $i < count($arr); $i++){
array_push($value, $numbers[$i]);
array_push($arr[$i], $numbers[$i]);
}
$numbers = array_diff($numbers, $value);
echo count($numbers);
$value = [];
}
}
show();
print_r($arr)
I want to specify the numbers for three empty arrays in $arr above, but need to iterate over each empty array like this:
Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
[2] => Array
(
[0] => 3
)
.......
)
My problem is the while loop, it runs forever and doesn't stop.
The expected output after running the function show() is:
$arr = [ [1,2,3],[4,5,6],[7,8,9] ]
You were getting infinite loop because numbers arrays was never becoming zero, instead keep a count of its length and decrement it at the end of each step
<?php
function show(){
$arr = array();
$numbers = array("1","2","3","4","5","6","7","8","9");
$value = array();
$c=count($numbers);
while( $c > 0){
for($i = 0; $i < $c; $i++){
if(!isset($arr[$i])){
$arr[$i]=array();
}
array_push($value,$numbers[$i]);
array_push($arr[$i],$numbers[$i]);
}
$c=$c-1;
$numbers=array_diff($numbers,$value);
$c= count($numbers);
$value = [];
}
return $arr;
}
print_r(show());
?>
Your comment requirement, use array_chunk()
<?php
function show(){
$arr = array();
$numbers = array("1","2","3","4","5","6","7","8","9");
return array_chunk($numbers, 3);
}
print_r(show());
enjoy!
Alright so Im trying to compare what array has bigger value but I want this code shorter, not running two foreach loops.
$one = array("test", "100");
$two = array("something", "200");
$distance1;
$distance2;
foreach($one as $val => $key) {
$distance1 = $val;
}
foreach($two as $val => $key) {
$distance2 = $val;
}
if($distance1 > $distance2)
I'm not entirely sure what you want to do, and it's been a while since I last wrote PHP, but I love this question and I would like to suggest 4 possible approaches:
1: use the arrays that you supplied (I believe this may be what you mean)
$one = array("test", "100");
$two = array("something", "200");
$distance1 = $one[1];
$distance2 = $two[1];
if($distance1 > $distance2)
2: associative arrays, and numbers for the values
$one = array(
"name" = > "test",
"distance" => 100
);
$two = array(
"name" => "something",
"distance" => 200
);
if ($one["distance"] > $two["distance"])
3: Using a foreach loop with $key and $val
$distances = array(
"test" => 100,
"something" => 200
);
$highestDistance = 0;
$highest = null;
foreach ($distances as $key => $val) {
if ($val >= highestDistance) {
$highestDistance = $val;
$highest = $key;
}
}
if ($highest === 'test')
4: objects and sorting:
$distances = array(
(object) array(
"name" => "test",
"distance" => 100
),
(object) array(
"name" => "something",
"distance" => 200
)
);
usort($distances, function($a, $b) { return $a - $b; });
if ($distances[0]->name === 'test')
Note that the conditions of the final if statements evaluate to false, as I believe is your intention (because 100 is not greater than 200).
You Can combine the 2 arrays
<?php
$one = array("test", "100");
$two = array("something", "200");
$result = array_merge($one , $two);
foreach($result as $val => $key) {
echo $val;
}
?>
I have a array
["item1","item2","item3"]
I want to get an array of ["1","2","3"]
how to get that in php
You need this
$arr = ["item1","item2","item3"];
for ($i = 0; $i < sizeof($arr); $i++) {
// replace "item" with ""
$arr[$i] = str_replace("item","",$arr[$i]);
}
<?php
$given_array = ["item1","item2","item3"];
$new_array = array();
foreach ($given_array as $arr) {
$new_array[] = intval(preg_replace('/[^0-9]+/', '', $arr), 10);
}
echo '<pre>';
print_r($new_array);
?>
1) Simply use
$res = str_replace('item', '', $array);
Output
$res
Array
(
[0] => 1
[1] => 2
[2] => 3
)
2) Using array_map()
$array = array_map(
function($str) {
return str_replace('item', '', $str);
},
$array
);
I have the following php code,
<?php
$first = array(1,2,3);
$last = array(4,5,6);
$k = 10;
echo json_encode(array('id' =>$k, 'name' => array( 'first' => $first, 'last' => $last)));
?>
I only get this result
{"id":10,"name":{"first":[1,2,3],"last":[4,5,6]}}
but I want the following format, so that I can access the data in javascript like name.first and name.last
{"id":10,"name":[{"first":1,"last":4},{"first":2,"last":5},{"first":3,"last":6}] }
can anyone help me out?
Thanks,
Pat
Use array_map to operate in the same time on the multiple arrays:
$array = array_map(function ($first, $last) { return array("first" => $first, "last" => $last); }, $first, $last);
echo json_encode(array('id' =>$k, 'name' => $array));
Sample code for a brute force solution for this:
$first = array(1,2,3);
$last = array(4,5,6);
$name = array();
for( $i = 0; $i < count($first); $i++) {
$name[$i]['first'] = $first[$i];
$name[$i]['last'] = $last[$i];
}
echo json_encode(array('id' =>$k, 'name' =>$name));
I need to get two arrays to merge into one while keeping all the keys in place and listing the values in an array like in this example:
$array1 = array('car' => '3', 'bus' => '2');
$array2 = array('dog' => '1', 'car' => '2', 'bird' => '9');
$merged = array(
'car' => array('3','2'),
'bus' => array('2',null),
'dog' => array(null,'1'),
'bird' => (null,'9')
);
function merge_common_keys(){
$arr = func_get_args();
$num = func_num_args();
$keys = array();
$i = 0;
for ($i=0; $i<$num; ++$i){
$keys = array_merge($keys, array_keys($arr[$i]));
}
$keys = array_unique($keys);
$merged = array();
foreach ($keys as $key){
$merged[$key] = array();
for($i=0; $i<$num; ++$i){
$merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
}
}
return $merged;
}
Usage:
$merged = merge_common_keys($array1,$array2);
PS. It can work with more than two arrays, just pass as many as you want as next arguments.
Something like this? http://php.net/array_merge_recursive