how to merge two arrays together and use json_encode - php

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));

Related

Remove a part of string from each element of an array in php

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 try to sort an array using sort() but it fails

if ( $_GET['_value'] == 'moto' )
{
$array[] = array('1' => 'Yamaha');
$array[] = array('2' => 'Suzuki');
$array[] = array('3' => 'Triumph');
$array[] = array('4' => 'KTM');
$array[] = array('5' => 'Honda');
$array[] = array('6' => 'Harley Davidson');
$array[] = array('7' => 'Buell');
$array[] = array('8' => 'MV Agusta');
$array[] = array('9' => 'Ducati');
$array[] = array('10' => 'Other');
}
$array = sort($array);
echo json_encode( $array );
that is the code i have and its pulled by a chained dropdown.
I want it to return the values sorted alphabetically but based on the code you see it returns an empty array. what could be the mistake I am making /
Your code fails because you have an array of arrays here.
You should either search for "sort php array by sub-array key"
Or you can try something like:
$array[1] = 'Yamaha';
$array[2] = 'Suzuki';
// ...
sort($array);
echo json_encode($array);
Your array contains arrays, hence cannot be sorted, try:
$array[1] = 'Yamaha';
$array[2] = 'Suzuki';
then sort($array)
You can use uasort() function
like:
function cmp($a, $b) {
$a = reset($a);
$b = reset($b);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
uasort($array, 'cmp')
It's not at all pretty but this does the job.
Unless you're constrained otherwise you should really use some of the other suggestions.
<?
if ( $_GET['_value'] == 'moto' ) {
$array[] = array('1' => 'Yamaha');
$array[] = array('2' => 'Suzuki');
$array[] = array('3' => 'Triumph');
$array[] = array('4' => 'KTM');
$array[] = array('5' => 'Honda');
$array[] = array('6' => 'Harley Davidson');
$array[] = array('7' => 'Buell');
$array[] = array('8' => 'MV Agusta');
$array[] = array('9' => 'Ducati');
$array[] = array('10' => 'Other');
foreach($array as $i => $v)
{
$v = array_values($v);
$sort[] = $v[0];
}
sort($sort);
$c = 0;
foreach($sort as $i => $v)
{
$c++;
$sorted[] = array($c=>$v);
}
echo json_encode($sorted);
}
?>

convert string to predefined 2D array [duplicate]

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);
}

How to get the uneven keys from an array?

I have to create a function that copy the array(that i pass to the function) with only uneven keys. Example:
$a = array(
'0' => '0',
'one => 'one',
'1' => '1',
'two' => 'two'
)
I have to get:
$result = array(
'one => 'one',
'two' => 'two'
)
I have created the follow function, it works, but maybe I need to optimize it(maybe exists a function that does this job). Advice?
private clean($values){
$vv = array();
$keys = array_keys($values);
for($i=1; $i < count($values); $i+=2) $vv[$keys[$i]] = $values[$keys[$i]];
return $vv;
}
Thanks
$even = range(0, count($array), 2);
source
UPDATE:
for ($i = 0, $c = count($array); $i <= $c; $i = $i + 2) {
$even = array_push($even, $array[$i]);
}
Try
$outputArray = array();
$keyToAdd = false;
foreach( $inputArray as $key => $value ) {
if( $keyToAdd ) {
$outputArray[$key] = $value;
}
$keyToAdd = !$keyToAdd;
}

PHP, Merging arrays with common keys

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

Categories