Associative Array From Multidimensional Array - php

I am new to PHP an needed little help. It may be easy for some but giving me a tough time.
I have an array
Array ( [0] => page-18 [1] => page-20 )
Which I would like to explode further by '-':
$mainStringBrk = array('page-18', 'page-20');
$finalArray = array();
foreach($mainStringBrk as $bString){
$mainStringBrkBrk = explode('-', $bString);
$finalArray[$mainStringBrkBrk[0]] = $mainStringBrkBrk[1];
}
echo '<pre>'; print_r($finalArray);
When I do, it outputs only the last key and value of array.
Array ( page => 20 )
My desired output is:
Array ( page => 18, page => 20 )
I am wondering if anyone can guide me in right direction.

You can't achieve the result you want as it is not possible to have an array with identical keys; this is why you only have one result in your output. You could change your output structure to a 2-dimensional array to work around this e.g.
$mainStringBrk = array('page-18', 'page-20');
$finalArray = array();
foreach($mainStringBrk as $bString){
$mainStringBrkBrk = explode('-', $bString);
$finalArray[$mainStringBrkBrk[0]][] = $mainStringBrkBrk[1];
}
print_r($finalArray);
Output:
Array
(
[page] => Array
(
[0] => 18
[1] => 20
)
)
Or you can adopt this structure if it is better suited to your needs:
$finalArray = array();
foreach($mainStringBrk as $bString){
$mainStringBrkBrk = explode('-', $bString);
$finalArray[] = array($mainStringBrkBrk[0] => $mainStringBrkBrk[1]);
}
print_r($finalArray);
Output:
Array
(
[0] => Array
(
[page] => 18
)
[1] => Array
(
[page] => 20
)
)
Demo on 3v4l.org

Related

Convert comma separated array to nested array with php function

I need to convert array_1 to array_2 with a PHP function. I tried many things but nothing works. I hope someone can help me out here. I think I need an each function or something to loop through the comma separated array and convert it into the array_2.
$array_1 = array (
0 => '6801,6800,7310,6795',
);
$array_2 = array (
0 =>
array (
0 => '6801',
1 => '6800',
2 => '7310',
3 => '6795',
),
);
Here a solution
<?php
$array_1 = array (
0 => '6801,6800,7310,6795',
);
$array_2 = array();
foreach ($array_1 as $value) {
array_push($array_2 , explode(",",$value));
}
print_r($array_2);
?>
The output that i got
Array ( [0] => Array ( [0] => 6801 [1] => 6800 [2] => 7310 [3] => 6795 ) )
Use PHP explode function. https://www.php.net/manual/de/function.explode.php
$newArray[] = explode(",", $array_1[0]);
// output
Array
(
[0] => Array
(
[0] => 6801
[1] => 6800
[2] => 7310
[3] => 6795
)
)
Just create a new array with a value returned by the explode function. Reset always returns the first value of the array regardless of the key.
$array_1 = array (0 => '6801,6800,7310,6795');
$newArray = [explode(",", reset($array_1))];

array_push adds another empty array after adding my array

I was working on a way to populate an empty array.
I have this code:
$array = array();
$month = 'enero';
array_push($array, $array[$month] = array('01'));
array_push($array['enero'], '02');
print_r($array);
This returns:
Array
(
[enero] => Array
(
[0] => 01
[1] => 02
)
[0] => Array
(
[0] => 01
)
)
The array [0] appears from nowhere and I don't know what to do. I have tried
array_push($array['enero'], '02');
But it does not work. How can I get the expected result:
Array
(
[enero] => Array
(
[0] => 01
[1] => 02
)
)
When in doubt, avoid array_push and just use [] notation. It has the advantage of automatically creating sub-arrays that don't exist (so no need to use $array[$month] = array();):
$array = array();
$month = 'enero';
$array[$month][] = '01';
$array[$month][] = '02';
print_r($array);
If you want to use array_push, you need to create the enero element first before attempting to push into it:
$array = array();
$month = 'enero';
$array[$month] = array();
array_push($array[$month], '01');
array_push($array[$month], '02');
print_r($array);
Output (for both pieces of code):
Array
(
[enero] => Array
(
[0] => 01
[1] => 02
)
)
Demo on 3v4l.org

Difference between two JSON strings in php and remove duplicate?

$json_str1 = '[{"13:00":"1"},{"14:00":"1"},{"15:30":"1"},{"16:30":"1"},{"1:00":"1"}]';
$json_str2 = '[{"13:00":"1"},{"14:00":"1"},{"15:30":"1"},{"12:30":"1"}]';
These are two JSON strings and I want the result like difference between them like {"1:00":"1"} and one more {"12:30":"1"}
The solution of this has a many aspects, cause there's 3 different values:
{"16:30":"1"},{"1:00":"1"}
{"12:30":"1"}
Firstly, you can convert your JSON string into array with json_decode($str,true):
json_decode($json_str1, true);
json_decode($json_str2, true);
Outputs like:
Array
(
[0] => Array
(
[13:00] => 1
)
...
Then create combined array with values like JSON object elements with foreach loop:
$str1 = [];
foreach($data1 as $row){
$str1[] = json_encode($row);
}
Outputs like:
Array
(
[0] => {"13:00":"1"}
[1] => {"14:00":"1"}
[2] => {"15:30":"1"}
[3] => {"16:30":"1"}
[4] => {"1:00":"1"}
)
...
Then you can find the difference between this two arrays, but, you need to do it in both ways (compare $array1 with $array2 and $array2 with $array1):
$dif1 = array_diff($str1, $str2);
$dif2 = array_diff($str2, $str1);
Outputs:
Array
(
[3] => {"16:30":"1"}
[4] => {"1:00":"1"}
)
Array
(
[3] => {"12:30":"1"}
)
Finally you can merge the result with:
$fin = array_merge($dif1, $dif2);
Outputs:
Array
(
[0] => {"16:30":"1"}
[1] => {"1:00":"1"}
[2] => {"12:30":"1"}
)
All of this you can put in a separate function like:
function getDifference2JSONstrings($jsonStr1, $jsonStr2){
$data1 = json_decode($jsonStr1, true);
$data2 = json_decode($jsonStr2, true);
$str1 = [];
$str2 = [];
foreach($data1 as $row){
$str1[] = json_encode($row);
}
foreach($data2 as $row){
$str2[] = json_encode($row);
}
return array_merge(array_diff($str1, $str2), array_diff($str2, $str1));
}
$res = getDifference2JSONstrings($json_str1, $json_str2);
print_r($res);
Outputs an array:
Array
(
[0] => {"16:30":"1"}
[1] => {"1:00":"1"}
[2] => {"12:30":"1"}
)
Demo

Merger Array Table

I have two array, I would like to merge them without duplicating in "name",
$array1[]= array(name['udi','ari'],id['1','2'])
$array2[]= array(name['udi','ari'],age['22','18'])
result
$arrayresult[]= array(name['udi','ari'],id['1','2'],age['22','18'])
Just simply use array_merge for merging both array as:
Example:
<?php
$array1 = array(
'name'=>array('udi','ari'),
'id'=>array('1','2'),
);
$array2 = array(
'name'=>array('udi','ari'),
'age'=>array('22','18'),
);
$newArr = array_merge($array1,$array2);
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[name] => Array
(
[0] => udi
[1] => ari
)
[id] => Array
(
[0] => 1
[1] => 2
)
[age] => Array
(
[0] => 22
[1] => 18
)
)
You can use first $result=array_merge($array1,$array2) and then use $result=array_unique($result) its remove duplicate value.
I think what you're looking for is array_merge:
http://php.net/manual/en/function.array-merge.php
$arrayresult = array_merge($array1,$array2);
should give you:
$arrayresult = array(name('udi','ari'),id('1','2'),age('22','18'))

PHP use of array_map array_shift to slice array into odd and even sub arrays

By definition, PHP's array_shift will return the first elem from the array and the array will downsize one.
I want to slice an array alternatingly into two sub-arrays, i.e index of 0,2,4,6,... and index of 1,3,5,7,...
I first break it into chunks of 2, then I use array_map to call array_shift. However, it is half correct (output below):
array1: Array ( [0] => greeting [1] => question [2] => response )
array2: Array ( [0] => Array ( [0] => greeting [1] => hello ) [1] => Array ( [0] => question [1] => how-are-you ) [2] => Array ( [0] => response [1] => im-fine ) )
Here's the code:
$a=array("greeting", "hello", "question", "how-are-you", "response", "im-fine");
$b=array_chunk($a, 2);
$c=array_map("array_shift", $b);
echo "array1: ";
print_r($c);
echo "array2: ";
print_r($b);
array2 does not seem to downsize after array_shift. Is this the correct behavior? How can I do what I intend to do?
Thanks
While this is already solved using array functions here is a low tech solution using a simple toggle to separate the odd and even elements...
$in = array("greeting", "hello", "question", "how-are-you", "response", "im-fine");
$i = 0;
$list = array();
foreach ($in as $text)
{
$list[$i][] = $text;
$i = 1 - $i;
}
print_r($list[0]);
print_r($list[1]);
Result...
Array ( [0] => greeting [1] => question [2] => response )
Array ( [0] => hello [1] => how-are-you [2] => im-fine )
Try this way to split your array alternatively EVEN and ODD keys, there may be many ways to do this, but this is my simple way using array_walk
$odd = [];
$even = [];
$both = [&$even, &$odd];
$array=["greeting", "hello", "question", "how-are-you", "response", "im-fine"];
array_walk($array, function($value, $key) use ($both) { $both[$key % 2][] = $value; });
print '<pre>';
print_r($even);
print_r($odd);
print '</pre>';
RESULT:
Success time: 0.02 memory: 24448 signal:0
<pre>Array
(
[0] => greeting
[1] => question
[2] => response
)
Array
(
[0] => hello
[1] => how-are-you
[2] => im-fine
)

Categories