creating new php array from two arrays by adding new keys values - php

I have below two arrays,
$category = array('available', 'notavailable' );
$values = array(1, 2 );
Now i want to get JSON output as below,
[{category: 'available', value:1}{category: 'notavailable', value:2}]
I tried using array_merge array_combine but could not got desired outlut with new Key values category and value,
How can i get that?
Thanks,

You can use array_map, if you have fixed keys:
<?php
$category = array('available', 'notavailable' );
$values = array(1, 2 );
$array = array_map(function($category, $value) {
return ['category' => $category, 'value'=>$value];
}, $category, $values);
echo "<pre>";
var_dump(json_encode($array));
echo "</pre>";
Output:
string(74) "[{"category":"available","value":1},{"category":"notavailable","value":2}]"

I think you must doing like this:
$result = array();
for ($i = 0; $i < count($category); $i++) {
$result[] = array(
'category' => $category[$i],
'value' => $values[$i]
);
}
echo json_encode($result);

Related

Get first number in array list

I use laravel. And then when from submitted, it pass value as array.
My question is, how i can split the value? I want number before '-' and after '-'.
I want just like below:
and
My code just like below
$form = $request->all();
$emelto = $form['emelto'];
$split = explode('-', $emelto );
but it shows error
explode() expects parameter 2 to be string, array given
Please someone can help me.
Explode each individual string as you tried.
Insert each number in it's respective column index in result.
Snippet:
<?php
$emelto = [
'4-2',
'11-5'
];
$data = [];
foreach($emelto as $str){
foreach(explode('-',$str) as $index => $s){
$data[$index] = $data[$index] ?? [];// assuming your PHP version supports ??
$data[$index][] = $s;
}
}
print_r($data);
You can use
$array1 = array();
$array2 = array();
foreach($request->emelto as $val){
$dataArray = explode('-', $val);
$array1[] = $dataArray[0];
$array2[] = $dataArray[1];
}
$emelto is an array and you are passing it to explode. You have to pass it like $emelto[0].
You should update your code with the below one.
<?php
$form = $request->all();
$emelto = $form['emelto'];
$array1 = explode('-', $emelto[0] );
$array2 = explode('-', $emelto[1] );
$array3 = array();
array_push($array3, $array1[0]);
array_push($array3, $array2[0]);
$array4 = array();
array_push($array4, $array1[1]);
array_push($array4, $array2[2]);
?>

PHP split array into 2 arrays by value

I'm having a hard time figuring out how to implement this so here it is. I have an array
$arr = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1",
2=>"POD2",
),
"quantity_received"=>array(
0=>5,
1=>10,
2=>20
)
);
I want to split the arrays into two. Into something like this.
$pod_2 = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1"
),
"quantity_received"=>array(
0=>5,
1=>10
));
$pod_1 = array("purchase_order_details_id"=>array(
2=>"POD2"
),
"quantity_received"=>array(
2=>20
));
Anyone has an idea on how to do this ? Any thoughts is appreciated. Thanks
I use array_intersect to find the POs in a loop of unique POs.
Then I use array_inyersect_key to get the quantity.
This requires only one iteration per unique Purchase_order_detali_id.
Meaning it has a much better performance than looping the full array.
Edit: added extract to create the two variables. But I would rather keep them in the array if I was you.
$pods = array_unique($arr["purchase_order_details_id"]);
Foreach($pods as $pod){
$PO = array_intersect($arr["purchase_order_details_id"], [$pod]);
$qt = array_intersect_key($arr["quantity_received"], $PO);
$new[$pod] = ["purchase_order_details_id" => $PO, "quantity_received" => $qt];
}
Var_dump($new);
extract($new);
https://3v4l.org/dBpuJ
Try with below code:
$array = array();
foreach($arr['purchase_order_details_id'] as $key => $val)
{
$array[$val]['purchase_order_details_id'][] = $val;
$array[$val]['quantity_received'][] = $arr['quantity_received'][$key];
}
echo "<pre>";
print_r($array);
echo "</pre>";
extract($array);
echo "<pre>";
print_r($POD1);
echo "</pre>";
echo "<pre>";
print_r($POD2);
echo "</pre>";
foreach ($arr as $key => $val) {
$size = ceil(count($val) / 2);
$arr2 = array_chunk($val, $size, true);
$pod_2[$key] = $arr2[0];
$pod_1[$key] = $arr2[1];
}
var_dump($pod_2);
var_dump($pod_1);

create multidimetional array associative array

I have an array
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
I want to convert this to
$multiarr=array(
[0]=>array(
['id']=>1,
['name']=>'abc'),
[1]=>array(
['id']=>2,
['name']=>'xyz'),
[2]=>array(
['id']=>3,
['name']=>'pqr')
);
id is key and the name is the value of the first array
how can I implement this optimistically
I have done this
$keys=array_keys($arr);
$values=array_values($arr) ;
$multiarr=array();
for($i=0; $i<count($keys); $i++)
{
$multiarr[$i]['id']=$keys[$i];
$multiarr[$i]['name']=$values[$i];
}
Thanks.
Should really be trying this yourself mate, but this should help:
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
$MultiArr = array();
$i = 0;
foreach($arr as $ID=>$Name){
$MultiArr[$i]['id'] = $ID;
$MultiArr[$i]['name'] = $Name;
$i++;
}
print_r($MultiArr);

Creating a dynamic hierarchical array in PHP

I have this general data structure:
$levels = array('country', 'state', 'city', 'location');
I have data that looks like this:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', ... )
);
I want to create hierarchical arrays such as
$hierarchy = array(
'USA' => array(
'New York' => array(
'NYC' => array(
'Central Park' => 123,
),
),
),
'Germany' => array(...),
);
Generally I would just create it like this:
$final = array();
foreach ($locations as $L) {
$final[$L['country']][$L['state']][$L['city']][$L['location']] = $L['count'];
}
However, it turns out that the initial array $levels is dynamic and can change in values and length So I cannot hard-code the levels into that last line, and I do not know how many elements there are. So the $levels array might look like this:
$levels = array('country', 'state');
Or
$levels = array('country', 'state', 'location');
The values will always exist in the data to be processed, but there might be more elements in the processed data than in the levels array. I want the final array to only contain the values that are in the $levels array, no matter what additional values are in the original data.
How can I use the array $levels as a guidance to dynamically create the $final array?
I thought I could just build the string $final[$L['country']][$L['state']][$L['city']][$L['location']] with implode() and then run eval() on it, but is there are a better way?
Here's my implementation. You can try it out here:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', 'state'=>'Blah', 'city'=>'NY', 'location'=>'Testing', 'count'=>54),
);
$hierarchy = array();
$levels = array_reverse(
array('country', 'state', 'city', 'location')
);
$lastLevel = 'count';
foreach ( $locations as $L )
{
$array = $L[$lastLevel];
foreach ( $levels as $level )
{
$array = array($L[$level] => $array);
}
$hierarchy = array_merge_recursive($hierarchy, $array);
}
print_r($hierarchy);
Cool question. A simple approach:
$output = []; //will hold what you want
foreach($locations as $loc){
$str_to_eval='$output';
for($i=0;$i<count($levels);$i++) $str_to_eval .= "[\$loc[\$levels[$i]]]";
$str_to_eval .= "=\$loc['count'];";
eval($str_to_eval); //will build the array for this location
}
Live demo
If your dataset always in fixed structure, you might just loop it
$data[] = [country=>usa, state=>ny, city=>...]
to
foreach ($data as $row) {
$result[][$row[country]][$row[state]][$row[city]] = ...
}
In case your data is dynamic and the levels of nested array is also dynamic, then the following is an idea:
/* convert from [a, b, c, d, ...] to [a][b][...] = ... */
function nested_array($rows, $level = 1) {
$data = array();
$keys = array_slice(array_keys($rows[0]), 0, $level);
foreach ($rows as $r) {
$ref = &$data[$r[$keys[0]]];
foreach ($keys as $j => $k) {
if ($j) {
$ref = &$ref[$r[$k]];
}
unset($r[$k]);
}
$ref = count($r) > 1 ? $r : reset($r);
}
return $data;
}
try this:
<?php
$locations = [
['country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'street'=>'7th Ave', 'count'=>123],
['country'=>'USA', 'state'=>'Maryland', 'city'=>'Baltimore', 'location'=>'Harbor', 'count'=>24],
['country'=>'USA', 'state'=>'Michigan', 'city'=>'Lansing', 'location'=>'Midtown', 'building'=>'H2B', 'count'=>7],
['country'=>'France', 'state'=>'Sud', 'city'=>'Marseille', 'location'=>'Centre Ville', 'count'=>12],
];
$nk = array();
foreach($locations as $l) {
$jsonstr = json_encode($l);
preg_match_all('/"[a-z]+?":/',$jsonstr,$e);
$narr = array();
foreach($e[0] as $k => $v) {
if($k == 0 ) {
$narr[] = '';
} else {
$narr[] = ":{";
}
}
$narr[count($e[0]) -1] = ":" ;
$narr[] = "";
$e[0][] = ",";
$jsonstr = str_replace($e[0],$narr,$jsonstr).str_repeat("}",count($narr)-3);
$nk [] = $ko =json_decode($jsonstr,TRUE);
}
print_r($nk);
Database have three field:
here Name conatin contry state and city name
id,name,parentid
Pass the contry result to array to below function:
$data['contry']=$this->db->get('contry')->result_array();
$return['result']=$this->ordered_menu( $data['contry'],0);
echo "<pre>";
print_r ($return['result']);
echo "</pre>";
Create Function as below:
function ordered_menu($array,$parent_id = 0)
{
$temp_array = array();
foreach($array as $element)
{
if($element['parent_id']==$parent_id)
{
$element['subs'] = $this->ordered_menu($array,$element['id']);
$temp_array[] = $element;
}
}
return $temp_array;
}

Adding values to an Associative array

I'm tring to add new values to an associative array dynamically and I need your help.
Here is a simple example :
$a = array();
$a["name"]= "n1";
$a["age"]= "age1";
$a["name"]= "n2";
$a["age"]= "age2";
The result is:
Array (2){["name"]=>string(2) "n2" ["age"]=>string(4) "age2" }
I want to add The first age and name and the second age and name to the array. What can I do??
If you want to maintain name <=> age relationship :
$a = array();
$a[] = array("name"=>"n1","age"=>"age1");
$a[] = array("name"=>"n2","age"=>"age2");
UPDATE : usage example below :
foreach ($a as $assoc) {
echo $assoc["name"],' is ',$assoc["age"],'.<br />';
}
$a = array();
array_push($a, array("name"=>"n1","age"=>"age1"));
array_push($a, array("name"=>"n2","age"=>"age2"));
array_push
$a = array();
$a["name"][]= "n1";
$a["age"][]= "age1";
$a["name"][]= "n2";
$a["age"][]= "age2";
You can do by this way
$a = array(
array(
'name' => 'n1',
'age' => 'age1'
),
array(
'name' => 'n2',
'age' => 'age2'
)
);
That's very easy and simple, you can do whatever you want with arrays!! Any doubts? Here you go:
$a = array();
if(is_array($a) && i_can_answer())
{
$keys = array('age', 'name');
$anotherArray = array();
if(is_array($anotherArray ) && i_know_multi_dimensional_arrays())
{
array_push($anotherArray, array("+18", "ILovePHP"));
$result1 = array_combine($keys, $anotherArray);
}
$otherAnotherArray = array();
if(is_array($otherAnotherArray) && i_am_not_tired())
{
array_push($otherAnotherArray , array("+18", "ILovePHP"));
$result2 = array_combine($keys, $otherAnotherArray);
}
$a = array_merge($result1, $result2);
}
print_r($a); //// hoooorrraaaaaaaaaay

Categories