php array merge and convert to json - php

I have two arrays (below). Is it possible to convert them into json string?
Array
(
[0] => size
[1] => color
)
Array
(
[0] => L
[1] => Black
)
Output structure should be:
[
{"name":"size","value":"L"},
{"name":"color","value":"Black"}
]
Thanks!

Sure:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
This gives you
[{"name":"size","value":"L"},{"name":"color","value":"Black"}]

this here should work:
$json = json_encode( array_combine( $array1, $array2 ) );

Something like this should work just how you want:
<?php
$keys = array("size", "color");
$values = array("L", "Black");
$array = array();
foreach ($keys as $i => $key) {
$array[] = array(
"name" => $key,
"value" => $values[$i]
);
}
$json = json_encode($array);
var_dump($json);
//string(62) "[{"name":"size","value":"L"},{"name":"color","value":"Black"}]"
?>

$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$result = array_combine($array1 , $array2);
$json = array();
foreach($result as $key => $val){
$json[] = array('name' => $key, 'value' => $value);
}
$json = json_encode($json);

I think you are looking for this:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
for($i=0;$i<sizeof($array1);$i++)
{
$array3[]=array($array1[$i]=>$array2[$i]);
}
echo json_encode($array3);
?>
Output:
[{"size":"L"},{"color":"Black"}]

Related

Dealing with array PHP

I am trying to sort the following arrays.
Array(s)
$fruits = array(
'mango',
'mango red',
'mango yellow',
'orange',
'banana',
'apple',
'apple red',
'apple green',
);
What I have done:
$data = array_flip( $fruits ); // flip array
$data = array_fill_keys( array_keys( array_flip( $data ) ), 'array(),' ); // fill array value: "array(),"
print_r( $data );
I want this result:
$fruits = array(
'mango' => array(
'red' => array(),
'yellow' => array(),
),
'orange' => array(),
'banana' => array(),
'apple' => array(
'red' => array(),
'green' => array(),
),
);
Does anybody know how to do this?
Hope you can understand the question. Thank you in advance.
Loop through the array, and split the string. Then recursively create nested arrays.
$result = array();
foreach ($fruits as $f) {
$f_array = explode(' ', $f);
$start = &$result;
foreach ($f_array as $word) {
if (!isset($start[$word])) {
$start[$word] = array();
}
$start = &$start[$word];
}
}
var_dump($result);
DEMO
Use the following approach(for your current array):
$result = [];
foreach ($fruits as $fruit) {
$parts = explode(' ', $fruit);
if (count($parts) == 1) {
$result[$fruit] = [];
} elseif (isset($result[$parts[0]])) {
$result[$parts[0]][$parts[1]] = [];
}
}
print_r($result);

Array Difference for multi dimentional array

I have two array
$array1 = array
(
array('A',0),
array('B',0),
array('C',0),
array('D',0),
array('E',0),
array('F',0),
)
$array2 = array
(
array('A',5),
array('B',6),
array('C',10),
array('F',23),
)
$array2 will be changing sometimes A keys is there or its not there. It is applied for all keys.
I want to create a new array or replace the array values in $array1 to
$array1 = array
(
array('A',5),
array('B',6),
array('C',10),
array('D',0),
array('E',0),
array('F',23),
)
Try something like below
if(count($array1) > count($array2)){
$tempArr1 = $array1;
$tempArr2 = $array2;
}else{
$tempArr1 = $array2;
$tempArr2 = $array1;
}
$newArr = array();
foreach($tempArr1 as $values){
$a = $values[0]; $n = $values[1];
foreach($tempArr2 as $key=>$val){
if($val[0] == $a){
$n = ($val[1] > $n) ? $val[1] : $n;
unset($tempArr2[$key]);
}
}
$newArr[] = array($a, $n);
}
print_r($newArr);
$array1 = array (
array('A',0),
array('B',0),
array('C',0),
array('D',0),
array('E',0),
array('F',0),
);
$array2 = array (
array('A',5),
array('B',6),
array('C',10),
array('F',23),
);
foreach( $array2 as $itemKey2 => $itemVal2 ) {
$found = false;
foreach( $array1 as $itemKey1 => $itemVal1 ) {
if( $itemVal1[0] == $itemVal2[0] ) {
$found = true;
$array1[$itemKey1][1] = $itemVal2[1];
break;
}
}
if( !$found )
$array1[] = $item2;
}
echo var_export( $array1, true );
In retrospect, this scenario seems needlessly complicated. Unless something else truly requires this structure, if possible use something like:
$array1 = array (
'A' => 0,
'B' => 0,
'C' => 0,
'D' => 0,
'E' => 0,
'F' => 0
);
$array2 = array (
'A' => 5,
'B' => 6,
'C' => 10,
'F' => 23
);
foreach( $array2 as $key => $val ) {
$array1[$key] = $val;
}

Fill an array in php with two array

I have two numeric arrays (these arrays will always have the same number of keys and values).
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = array(value of the $array1 => $value of the array2);
If I write a while and fill the $array_final, it only fills with the last key and value
So it's like:
for ($i = 0; $i < count($array(1))
{
$array_final = array($array1[$i] => $array2[$i]);
}
$array_final = array("key2" => "value2");
But I want:
$array_final = array("key1" => "value1", "key2" => "value2");
You want array_combine
It does exatcly what you need
So basically
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = array_combine($array1, $array2);
for ($i=0; $i< sizeof($array1) && $i< sizeof($array2) ; $i++)
{
$array_final[$array1[$i]] =$array2[$i];
}
You may try below code.
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = combine_if_same_keys($array1,$array2);
print_r($array_final);
function combine_if_same_keys( $array_one, $array_two ) {
$expected = false;
ksort($array_one);
ksort($array_two);
$diff = array_diff_key($array_one, $array_two);
if( empty($diff) && count($array_one) == count($array_two) ) {
$expected = array_combine( $array_one, $array_two );
}
return $expected;
}

PHP : How to extract value of multidimensionnal array?

I have this multidimensional array and I would like to get from it only array('13', '11', '12', '10'). How can I get this?
array
0 =>
array
'id' => '13'
1 =>
array
'id' => '11'
2 =>
array
'id' => '12'
3 =>
array
'id' => '10'
for($i =0 ;$i<count($array);$i++)
{
echo $array[$i]['id'];
}
try
$values = array();
foreach($arr as $inner)
{
$values[] = $inner['id'];
}
// $values should now hold array(13, 11, 12, 10)
Try this :
$array = your array
$result = call_user_func_array('array_merge_recursive', $array);
echo "<pre>";
print_r($result['id']);
Try this :
<?php
$array=Array('0'=>Array('id'=>"1"),'1'=>Array('id'=>"2"),'2'=>Array('id'=>"3"),'4'=>Array('id'=>"4"));
$arr=Array();
for($i =0 ;$i<3;$i++)
{
$arr[$i]=$array[$i]['id'];
}
print_r(implode(',',$arr));
?>
O/p:
1,2,3
$values = array();
foreach(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr)) as $key => $value) {
if ($key == 'id') $values[] = $value;
}
var_dump($values);

Counting blanks when merging assoctiative arrays

I'm trying to merge these 2 arrays
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
into an array that looks like this
$arr1 = array(
'a' => array("1", "9"),
'b' => array("2", "8"),
'c' => array("3", ""),
'd' => array("", "7")
);
The tricky part is the blanks. I need to preserve them in place.
Thanks
function merge()
{
$array_of_arrays = func_get_args();
//get all the unique keys
$final_array_keys = array_keys( call_user_func_array( "array_merge", $array_of_arrays ) );
//make final array
$final_array = array();
foreach( $final_array_keys as $key ) {
foreach( $array_of_arrays as $current_array ) {
$final_array[$key][] = array_key_exists( $key, $current_array ) ? $current_array[$key] : "";
}
}
return $final_array;
}
Try this:
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
$keys = array();
$merged = array()
for($arr1 as $key=>$val)
{
array_push($keys,$key);
}
for($arr2 as $key=>$val)
{
array_push($keys,$key);
}
for($key in keys)
{
$merged[$key] = array("","");
if(isset($arr1[$key])) $merged[$key][0] = $arr1[$key];
if(isset($arr2[$key])) $merged[$key][1] = $arr2[$key];
}
foreach (array_merge($arr1, $arr2) as $key => $val)
{
$result[$key] = array("{$arr1[$key]}", "{$arr2[$key]}");
}
var_dump($result);
here's my suggestion. It'll combine an arbitrary number of arrays according to what you described.
error_reporting(E_ALL | E_STRICT);
header('Content-Type: text/plain');
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
$arr = combine($arr1, $arr2);
print_r($arr);
function combine() {
$keys = array();
foreach (func_get_args() as $arr) {
if (is_array($arr)) {
$keys += $arr;
}
}
$keys = array_keys($keys);
$values = array_pad(array(), count($keys), array());
$ret = array_combine($keys, $values);
foreach (func_get_args() as $arr) {
foreach ($keys as $k) {
$v = array_key_exists($k, $arr) ? $arr[$k] : '';
array_push($ret[$k], $v);
}
}
return $ret;
}
Output:
Array
(
[a] => Array
(
[0] => 1
[1] => 9
)
[b] => Array
(
[0] => 2
[1] => 8
)
[c] => Array
(
[0] => 3
[1] =>
)
[d] => Array
(
[0] =>
[1] => 7
)
)
I like cletus's approach, so I've just made sure it works :)
function combine() {
$keys = array();
foreach (func_get_args() as $arr) {
if (is_array($arr)) {
$keys = array_merge($keys, array_keys($arr));
}
}
$keys = array_unique($keys);
$values = array_pad(array(), count($keys), array());
$ret = array_combine($keys, $values);
foreach (func_get_args() as $arr) {
foreach ($keys as $k) {
$v = '';
if (array_key_exists($k, $arr)){
$v = $arr[$k];
}
array_push($ret[$k], $v);
}
}
return $ret;
}

Categories