I have data array on this way:
array(3) {
[0]=>
array(2) {
["name"]=>
string(13) "Register Page"
["id"]=>
string(1) "5"
}
[1]=>
array(2) {
["name"]=>
string(10) "Login Page"
["id"]=>
string(1) "6"
}
[2]=>
NULL
}
My goal is to get from the array above something like this:
array(5,6,null);
Thanks!
Look at the PHP function array_map
$array = [
["name" => "Register Page", "id" => 5 ],
["name" => "Login Page", "id" => 6 ],
NULL
];
$ids = array_map( function($rec) { return $rec['id'] ?? null; }, $array);
Assuming your data is in $a:
foreach ( $a as $a2 ) {
if ( is_array($a2) && $a2['id'] ) {
$r[] = $a2['id']; // or (int) $a2['id'] if you want to cast it to an int
} else {
$r[] = NULL;
}
}
Related
I want to merge two different array data in one array, but i'm confuse how to use array_push in this case.
this is example of my data input:
["author"]=>
array(2) {
[0]=>
string(1) "John"
[1]=>
string(1) "Doe"
}
["title"]=>
array(2) {
[0]=>
string(1) "book a"
[1]=>
string(1) "book b"
}
And the result in one array that i mean, like this:
["books"]=>
array(2) {
[0] =>
array(2) {
["author"]=>
string(1) "John"
["title"]=>
string(1) "book a"
}
[1] =>
array(2) {
["author"]=>
string(1) "Doe"
["title"]=>
string(1) "book b"
}
}
I already try using this way but it just return 1 from each array:
$data['books'] = [];
array_push($data['books'], [
'author' => $data['author'],
'title' => $data['title']
]);
if (isset($data['books'])) {
foreach ($data['books'] as $k => $v) {
$data['books'][$k]['author'] = (int)$v['author'];
$data['books'][$k]['title'] = (int)$v['title'];
}
}
result:
["books"]=>
array(1) {
[0]=>
array(2) {
["author"]=>
int(1)
["title"]=>
int(1)
}
}
You have to transpose your arrays with the keys in mind.
function transpose(array $arr){
$transArr = [];
foreach($arr as $keyRow => $subArr) {
foreach($subArr as $keyCol => $value) {
$transArr[$keyCol][$keyRow] = $value;
}
}
return $transArr;
}
This function can be used universally for similar problems. The function comes from this class.
How to use:
$input = [
"author"=> ["John","Doe"],
"title" => ["book a","book b"],
];
$books = transpose($input);
echo '<pre>';
var_export($books);
Or if you want to use the class:
$books = tableArray::create($input)
->transpose()
->fetchAll()
;
Output:
array (
0 =>
array (
'author' => 'John',
'title' => 'book a',
),
1 =>
array (
'author' => 'Doe',
'title' => 'book b',
),
)
If "author" and "title" exist as two arrays, $ input must first be created like this:
$input = ['author' => $arrayAuthor, 'title' => $arrayTitle];
I need to convert simple array to nested array according to specific rules. I've achived it but I'm looking for better solution.
SIMPLE:
array(4) {
[0]=>
array(2) {
["id"]=>
string(2) "11"
["type"]=>
int(3)
}
[1]=>
array(2) {
["id"]=>
string(2) "10"
["type"]=>
int(2)
}
[2]=>
array(2) {
["id"]=>
string(1) "1"
["type"]=>
int(1)
}
[3]=>
array(2) {
["id"]=>
string(1) "0"
["type"]=>
int(1)
}
}
EXPECTED EFFECT:
array(1) {
[0]=>
array(2) {
["type"]=>
int(1)
["child"]=>
array(1) {
[1]=>
array(2) {
["type"]=>
int(1)
["child"]=>
array(1) {
[10]=>
array(2) {
["type"]=>
int(2)
["child"]=>
array(1) {
[11]=>
array(2) {
["type"]=>
int(3)
["child"]=>
array(0) {
}
}
}
}
}
}
}
}
}
MY SOLUTION (not very satisfying):
$nestedArray = [];
foreach ($simpleArray as $item)
{
if (!empty($nestedArray))
{
$array = $nestedArray;
reset($array);
$firstKey = key($array);
}
$nestedArray[$item['id']]['child'] = $nestedArray;
$nestedArray[$item['id']]['type'] = $item['type'];
if (!empty($firstKey))
{
unset($nestedArray[$firstKey]);
}
}
As I said, I'm looking for more elegant way to achieve that. Rule are very simply: every next item is child of previous.
You could use recursion:
function nest($arr) {
return count($arr) ? ["type" => array_pop($arr)["type"], "child" => nest($arr)] : [];
}
With your example input, it would look like this:
$simpleArray = [
["id" => "11", "type" => 3],
["id" => "10", "type" => 2],
["id" => "1", "type" => 1],
["id" => "0", "type" => 1]
];
function nest($arr) {
return count($arr) ? ["type" => array_pop($arr)["type"], "child" => nest($arr)] : [];
}
$nested = nest($simpleArray));
$nested will have the following value:
[
"type" => 1,
"child" => [
"type" => 1,
"child" => [
"type" => 2,
"child" => [
"type" => 3,
"child" => []
]
]
]
]
I have array mentioned below, I will have value always multiple of 3.
$xyz = [
["name" => "abc"],
["name" => "snds"],
["name" => ""),
["number"=> "452"],
["number" => "845120"],
["number" => "84514513200"],
["email" => "ddddf"],
["email" => "dkskns"],
["email" => "kjnksdnkds"]
];
but this is not the proper format for me to perform further operations, so I want this array like mentioned below.
$abc = [
[
"name" => "abc",
"number" => '452',
"email" => "ddddf"
],
[
"name" => "snds",
"number" => "845120",
"email" => "dkskns"
],
[
"name" => "",
"number" => "84514513200",
"email" => "kjnksdnkds"
]
];
note: the array length is dynamic but it will always be multiple of 3
One possibility could be to use the modulo % operator.
In the foreach the value is an array and you could use array_keys to get the key and reset to get the value of the first array element.
$result = [];
$count = 0;
foreach ($xyz as $value) {
if ($count%3 === 0) {
$count = 0;
}
$result[$count][array_keys($value)[0]] = reset($value);
$count++;
}
Demo
That will give you:
array(3) {
[0]=>
array(3) {
["name"]=>
string(3) "abc"
["number"]=>
string(3) "452"
["email"]=>
string(5) "ddddf"
}
[1]=>
array(3) {
["name"]=>
string(4) "snds"
["number"]=>
string(6) "845120"
["email"]=>
string(6) "dkskns"
}
[2]=>
array(3) {
["name"]=>
string(0) ""
["number"]=>
string(11) "84514513200"
["email"]=>
string(10) "kjnksdnkds"
}
}
This will do:
$result = array_map('array_merge', ...array_chunk($xyz, count($xyz) / 3));
I have an array that is like this:
array(3) {
[0]=>
array(2) {
["id"]=>
string(2) "10"
["name"]=>
string(5) "city1"
}
[1]=>
array(2) {
["id"]=>
string(2) "11"
["name"]=>
string(5) "city2"
}
[2]=>
array(2) {
["id"]=>
string(2) "12"
["name"]=>
string(5) "city3"
}
}
I need to add another value that's called "status" to each of them. So that it basically becomes:
[0]=>
array(3) {
["id"]=>
string(2) "10"
["name"]=>
string(5) "city1"
["status"]=>
string(1) "1"
}
The status is dynamic and may vary for each item, so I need to call a function like this:
$status = getStatus($id);
That $id I am getting also from each item in that array.
How would I do this best? I understand I need to loop through the array, but how do I then add each correct response from getStatus to the correct array item?
Any help is greatly appreciated :)
Try this...
foreach($array $key=>$value){
$array[$key]['status']=1;
}
Demo......
I added a dummy function getStatus just to have an example, since you said that getStatus is dynamic might as well give you an example of that, you just have update to your own need of that function. Try this:
$data =
array(
array(
"id" => "10",
"name" => "city1"
),
array(
"id" => "11",
"name" => "city2"
),
array(
"id" => "13",
"name" => "city3"
)
);
echo '<pre>';
print_r($data);
echo '</pre>';
function getStatus($id) {
if($id == "10") {
$status = "1";
} else if($id == "11") {
$status = "2";
} else if($id == "13") {
$status = "3";
}
return $status;
}
foreach($data as $key => $values) {
$data[$key]["status"] = getStatus($data[$key]["id"]);
}
echo '<pre>';
print_r($data);
echo '</pre>';
This question already has answers here:
How to GROUP BY and SUM PHP Array? [duplicate]
(2 answers)
Closed 5 months ago.
given this array:
array(40) {
[0]=>
array(10) {
["item"]=>
string(5) "AABBCC"
["quants"]=>
string(1) "1"
}
[1]=>
array(10) {
["item"]=>
string(5) "AABBCC"
["quants"]=>
string(1) "1"
}
[2]=>
array(10) {
["item"]=>
string(5) "SLF02"
["quants"]=>
string(1) "1"
}
[3]=>
array(10) {
["item"]=>
string(5) "SLF02"
["quants"]=>
string(1) "3"
}
}
how without using a foreach do I end up with this output:
array(40) {
[0]=>
array(10) {
["item"]=>
string(5) "AABBCC"
["quants"]=>
string(1) "2"
}
[1]=>
array(10) {
["item"]=>
string(5) "SLF02"
["quants"]=>
string(1) "3"
}
}
are there any array_sum functions to do this with a multidimensional array like this in php?
This is a bad idea, but seemed like a fun challenge to do without a foreach:
$arr =
[
[
"item" =>"AABBCC",
"quants" => "1",
],
[
"item" => "AABBCC",
"quants" => "1",
],
[
"item" => "SLF02",
"quants" => "1",
],
[
"item" => "SLF02",
"quants" => "3",
]
];
$arr = array_values(call_user_func_array("array_merge", array_map(function($i) use ($arr) {
return [$i["item"] => ["item" => $i["item"], "quants" => array_reduce(
array_filter($arr, function($j) use ($i) {
return $j["item"] == $i["item"];
}), function($carry, $item) {
return $carry + $item["quants"];
})
]];
}, $arr)));
var_dump($arr);
/*
array(2) {
[0]=>
array(2) {
["item"]=>
string(6) "AABBCC"
["quants"]=>
int(2)
}
[1]=>
array(2) {
["item"]=>
string(5) "SLF02"
["quants"]=>
int(4)
}
}
*/
Here's my approach:
<?php
$array = array(
array('item'=>'AABBCC','quants'=>1),
array('item'=>'AABBCC','quants'=>1),
array('item'=>'SLF02','quants'=>1),
array('item'=>'SLF02','quants'=>3),
);
$summed_array = array();
foreach($array as $row){
$key = $row['item'];
if(!isset($summed_array[$key])){
$summed_array[$key] = array(
'item' => $row['item'],
'quants' => 0
);
}
$summed_array[$key]['quants'] += $row['quants'];
}
// turn the array back to a 0 based array
$summed_array = array_values($summed_array);
echo '<pre>',print_r($summed_array),'</pre>';