Padding data for sometimes missing object index

时间:2019-01-18 18:51:51

标签: php arrays object foreach

I have an array where I'm looping on an object

foreach ($product->info->details as $details) {

    $skuItem[] = $details->dtl1;
    $skuItem[] = $details->dtl2;
    $skuItem[] = $details->dtl3;

}

The object it loops on is structured this way

"details": {
  "1": {
    "dtl1": "123",
    "dtl2": "TEst",
    "dtl3": "123"
  },
  "2": {
    "dtl1": "12",
    "dtl2": "Test",
    "dtl3": "153"
  }
},

The thing is, it can only have up to 2 of those sets but sometimes it has only one.

Is there a way to accomodate in my foreach loop so that if there is only one then I can basically 'dummy up' a second set with all zeroes? I'm mapping this to a file and need to make sure I'm at least always mapping all 6 values

So if the object looks like

"details": {
  "1": {
    "dtl1": "123",
    "dtl2": "TEst",
    "dtl3": "123"
  }

I would want to create my array like

0 => "123",
1 => "TEst",
2 => "123"
3 => "0",
4 => "0",
5 => "0"

2 个答案:

答案 0 :(得分:3)

After the foreach, you can pad your array with zero:

foreach ($product->info->details as $details) {
    $skuItem[] = $details->dtl1;
    $skuItem[] = $details->dtl2;
    $skuItem[] = $details->dtl3;
}

Array now contains:

0 => "123"
1 => "TEst"
2 => "123"

Now run:

$skuItem = array_pad($skuItem, 6, 0);

This will add zeros to the end of the array until you get 6 items in it, so the array now contains:

0 => '123'
1 => 'TEst'
2 => '123'
3 => 0
4 => 0
5 => 0

If you want string zero instead, then just pass that as the 3rd arg:

$skuItem = array_pad($skuItem, 6, '0');

Yields:

0 => '123'
1 => 'TEst'
2 => '123'
3 => '0'
4 => '0'
5 => '0'

答案 1 :(得分:0)

You can create a template of what you want and replace with what you create in the loop:

$skuItem = array_replace(array_fill(0, 6, 0), $skuItem);

array_pad is probably better for this trivial example, but consider if you have a variety of values:

$temp = array('x', 'y', 'z', 'x', 'y', 'z');
$skuItem = array_replace($temp, $skuItem);

Or:

$temp = array('x', 'y', 'z');
if(count($skuItem) != 6) {
    $skuItem = array_merge($skuItem, $temp);
}